通过MySQL中的查询提供缺失值

时间:2014-11-26 10:57:09

标签: mysql

我在MySQL数据库中有一个表,我从中查询。我在查询特定月份的日期和销售数量。我的查询如下:

SELECT DATE_FORMAT(time,'%b-%y') AS "date", COUNT(*) AS "value"
FROM table
WHERE time_in BETWEEN concat('2014-01-01',' 00:00:00') AND concat('2014-11-25',' 23:59:59')
GROUP BY month(time);

注意:我知道这种情况下的concat是完全没必要的,我将它们替换为“?”在我的PHP后端进行数据绑定。

此查询的结果看起来像JSON:

[
{"date":"Feb-14","value":"2"},
{"date":"Mar-14","value":"1"},
{"date":"May-14","value":"1"},
{"date":"Jun-14","value":"1"},
{"date":"Jul-14","value":"2"},
{"date":"Sep-14","value":"1"},
{"date":"Oct-14","value":"1"},
{"date":"Nov-14","value":"1"}
]

正如你所看到的,我错过了几个月(1月,4月等)。我的问题是,是否有一种方法可以通过查询提供这些缺失的月份并填充值为0?我希望我的输出看起来像这样:

[
{"date":"Jan-14","value":"0"},
{"date":"Feb-14","value":"2"},
{"date":"Mar-14","value":"1"},
{"date":"Apr-14","value":"0"},
{"date":"May-14","value":"1"},
{"date":"Jun-14","value":"1"},
{"date":"Jul-14","value":"2"},
{"date":"Aug-14","value":"0"},
{"date":"Sep-14","value":"1"},
{"date":"Oct-14","value":"1"},
{"date":"Nov-14","value":"1"}
]

1 个答案:

答案 0 :(得分:0)

要扩展我的评论,您可以执行以下操作: -

SELECT  DATE_FORMAT(DATE_SUB(NOW(), INTERVAL month_cnt.iCnt MONTH), '%b-%y') AS MonthYear, COUNT(id)
FROM
(SELECT 0 iCnt UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION SELECT 10 UNION SELECT 11) month_cnt
LEFT OUTER JOIN table
ON MONTH(DATE_SUB(NOW(), INTERVAL month_cnt.iCnt MONTH)) = MONTH(table.time_in)
AND YEAR(DATE_SUB(NOW(), INTERVAL month_cnt.iCnt MONTH)) = YEAR(table.time_in)
GROUP BY MonthYear

这有一个返回数字0到11的子查询。然后,根据与当前日期月份相同的数据月份减去由当前日期返回的数字,将此子查询与您的数据表连接起来。子查询。然后它计算该月/年的表中存在的记录