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

前端 未结 2 960
旧巷少年郎
旧巷少年郎 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: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
    

提交回复
热议问题