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

前端 未结 2 938
旧巷少年郎
旧巷少年郎 2021-01-03 06:43

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 da

相关标签:
2条回答
  • 2021-01-03 07:10

    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.

    0 讨论(0)
  • 2021-01-03 07:11

    Unfortunately, MySQL lacks a way to generate a rowset of given number of rows.

    You can create a helper table:

    CREATE TABLE t_day (day INT NOT NULL PRIMARY KEY)
    
    INSERT
    INTO    t_day (day)
    VALUES  (1),
            (2),
            …,
            (31)
    

    and use it in a JOIN:

    SELECT  day, COUNT(*)
    FROM    t_day
    JOIN    p_community e
    ON      day BETWEEN DATE(e.start) AND IF(DATE(e.end), DATE(e.end), DATE(e.start))
    GROUP BY
            day
    

    Or you may use an ugly subquery:

    SELECT  day, COUNT(*)
    FROM    (
            SELECT  1 AS day
            UNION ALL
            SELECT  2 AS day
            …
            UNION ALL
            SELECT  31 AS day
            ) t_day
    JOIN    p_community e
    ON      day BETWEEN DATE(e.start) AND IF(DATE(e.end), DATE(e.end), DATE(e.start))
    GROUP BY
            day
    
    0 讨论(0)
提交回复
热议问题