简体   繁体   中英

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 (eg first of the month to last day of the month) and then group by that range (ie 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM