如何编写按日期接收数据组的查询?

时间:2018-02-20 15:26:30

标签: mysql sql

我写了一个简单的查询

SELECT date, count(user) as count FROM sessions GROUP BY date;

回应就像那样

enter image description here

但是,我希望看到每个日期,如果日期不存在,行必须像这样

2018-02-01 | 0
2018-02-02 | 0
2018-02-03 | 0
2018-02-04 | 0
2018-02-05 | 1503582
2018-02-06 | 0
2018-02-06 | 0
2018-02-08 | 5612270
...
...
...
2018-02-31 | 0

我怎样才能重写我的查询以获取飞蛾每天的数据?

1 个答案:

答案 0 :(得分:5)

您需要先生成日历,然后使用表格sessiondate列加入其行。下面的子查询将根据@START_DATE变量中设置的值生成所有1个月。

SET  @START_DATE  = '2018-01-01';  -- set your starting date here

SELECT  a.`DATE`,
        COUNT(b.user) AS `COUNT`
FROM
        (
            SELECT DATE(cal.date) `DATE` 
            FROM ( 
                SELECT @START_DATE + INTERVAL xc DAY AS date 
                FROM ( 
                      SELECT @xi:=@xi+1 as xc from 
                      (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc1, 
                      (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc2, 
                      (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc3, 
                      (SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4) xc4, 
                      (SELECT @xi:=-1) xc0 
                ) xxc1 
            ) cal 
            WHERE cal.date <= DATE_ADD(DATE_ADD(@START_DATE, INTERVAL 1 MONTH), INTERVAL -1 DAY)
        ) a
        LEFT JOIN sessions b
            ON a.`DATE` = b.`DATE`
GROUP   BY a.`DATE`
ORDER   BY a.`DATE`

这里是Demo

生成日期的子查询是从这个article: Generating a Series of Dates in MySQL借来的,并稍加修改以允许用户输入开始日期。