Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL to get the count of rows that fall on a date for each day of a month

Tags:

sql

mysql

I have a table that contains a list of community events with columns for the days the event starts and ends. If the end date is 0 then the event occurs only on the start day. I have a query that returns the number of events happening on any given day:

SELECT COUNT(*) FROM p_community e WHERE 
    (TO_DAYS(e.date_ends)=0 AND DATE(e.date_starts)=DATE('2009-05-13')) OR
    (DATE('2009-05-13')>=DATE(e.date_starts) AND DATE('2009-05-13')<=DATE(e.date_ends))

I just sub in any date I want to test for "2009-05-13".

I need to be be able to fetch this data for every day in an entire month. I could just run the query against each day one at a time, but I'd rather run one query that can give me the entire month at once. Does anyone have any suggestions on how I might do that?

And no, I can't use a stored procedure.

like image 849
ChiperSoft Avatar asked Dec 08 '22 07:12

ChiperSoft


1 Answers

Try:

SELECT COUNT(*), DATE(date) FROM table WHERE DATE(dtCreatedAt) >= DATE('2009-03-01') AND DATE(dtCreatedAt) <= DATE('2009-03-10') GROUP BY DATE(date);

This would get the amount for each day in may 2009.

UPDATED: Now works on a range of dates spanning months/years.

like image 187
Greg Avatar answered Dec 10 '22 12:12

Greg