显示mysql查询中缺少日期的计数

时间:2014-11-30 09:29:27

标签: mysql sql date datetime

运行以下查询后:

SELECT 
    DATE_FORMAT( added_datetime, '%Y-%m-%d' ) AS date, 
    SUM( gender = 'male' ) AS male, 
    SUM( gender = 'female' ) AS female
FROM social_user 
WHERE social_network = 'FBuser' 
AND date( added_datetime ) BETWEEN date('2014-11-18') AND date('2014-11-20')
GROUP BY date( added_datetime )

我得到了这个结果:

date        | male | female
------------+------+--------
2014-11-19  |    2 |      0

但我需要一些不同的东西,比如这个截图:

date        | male | female
------------+------+--------
2014-11-18  |    0 |      0
2014-11-19  |    1 |      0
2014-11-20  |    2 |      0
2014-11-21  |    0 |      0
...    
...

我需要在结果集中使用所有日期,这是我在运算符之间使用的。

抱歉我的英语不好,而且附件图片的名声不够。

1 个答案:

答案 0 :(得分:2)

数据中不存在的日期不会神奇地出现在结果中。一种解决方案是创建一个日期表,其中包含很长时间内的所有日期:

CREATE TABLE datelist (DATE DATETIME NOT NULL PRIMARY KEY);
-- dates in the past
INSERT INTO datelist VALUES ('2014-11-18');
INSERT INTO datelist VALUES ('2014-11-19');
INSERT INTO datelist VALUES ('2014-11-20');
INSERT INTO datelist VALUES ('2014-11-21');
-- dates in the future

并在JOIN查询中使用它:

SELECT
    datelist.date,
    SUM(gender = 'male') AS male,
    SUM(gender = 'female') AS female
FROM datelist
LEFT JOIN social_user ON datelist.date = DATE(social_user.added_datetime)
WHERE datelist.date BETWEEN '2014-11-18' AND '2014-11-20' AND (
    social_user.id /* or whatever primary key */ IS NULL OR social_network = 'FBuser'
)
GROUP BY datelist.date

示例输出:

date                 male  female
-------------------  ----  ------
2014-11-18 00:00:00  NULL  NULL
2014-11-19 00:00:00  2     0
2014-11-20 00:00:00  1     2

在上面的示例中,两个NULL列表示当天没有匹配的social_user记录。调整WHERE子句以包含此类行。