Tom
Tom

Reputation: 29

MySQL query to count rows grouped by date range

all. I have a table with a date column that is either null or contains the date of an event. I am trying to get a count of how many of those dates fall within a given range (e.g. first of the month to last day of the month) and then group by that range (i.e. group by month)

If I were to do it for a single month, it would look like this:

SELECT count(*)
FROM my_table
WHERE my_table.event_date > 1530403200 and my_table.event_date < 1530403200
/* 7/1/2018 to 7/31/2018 */

So what I'd really like is a query to give me results grouped by month with the count of those total rows within each month, like:

:
6/1/2018 - 6/30/2018, 8650
7/1/2018 - 7/31/2018, 9180
:
etc.

Thank you for any advice.

Upvotes: 0

Views: 56

Answers (1)

Sebastian Brosch
Sebastian Brosch

Reputation: 43604

You can use something like the following:

SELECT
    MONTH(FROM_UNIXTIME(event_date)) AS month,
    MIN(FROM_UNIXTIME(event_date)) AS first_date,
    MAX(FROM_UNIXTIME(event_date)) AS last_date, 
    COUNT(*) AS cnt_dates
FROM my_table
WHERE FROM_UNIXTIME(my_table.event_date) > '2018-08-01' 
    AND FROM_UNIXTIME(my_table.event_date) < '2018-08-15' 
    AND NOT my_table.event_date IS NULL
GROUP BY MONTH(FROM_UNIXTIME(event_date))

demo: https://www.db-fiddle.com/f/nNVBtJgpKkiCcf7B9GPCEN/0

Upvotes: 2

Related Questions