我正在尝试从每个月的日期开始计数。
SELECT COUNT(*) AS cnt, DATE_FORMAT(onBoardDateTime,'%Y-%m-01') AS date
FROM paDatabase
WHERE YEAR(onBoardDateTime) > '2015'
GROUP BY MONTH(onBoardDateTime)
我还要包含count = 0的月份。因此结果应为:
月| cnt
2015-01 | 10
2015-02 | 31
2015-03 | 0
2015-04 | 5
等。
谢谢
答案 0 :(得分:0)
尝试一下:
SELECT coalesce(COUNT(*), 0) AS cnt, DATE_FORMAT(onBoardDateTime,'%Y-%m-01') AS date
FROM paDatabase
WHERE YEAR(onBoardDateTime) > '2015'
GROUP BY MONTH(onBoardDateTime)
(未经测试)。
答案 1 :(得分:0)
您只能选择数据库中存在的数据。要获取其中没有数据的月份,请列出您感兴趣的月份,然后查找没有数据的月份。常见的解决方案是使用日历表,其中列出了您需要的所有月份/日期。
SELECT COUNT(*) AS cnt, DATE_FORMAT(onBoardDateTime,'%Y-%m-01') AS date
FROM paDatabase
WHERE YEAR(onBoardDateTime) > '2015'
GROUP BY DATE_FORMAT(onBoardDateTime,'%Y-%m-01')
UNION
SELECT 0, m
FROM CALENDAR_MONTHS
WHERE YEAR(m)>2015 AND m NOT IN (
SELECT CAST(DATE_FORMAT(onBoardDateTime,'%Y-%m-01') as date) AS date
FROM paDatabase
WHERE YEAR(onBoardDateTime) > '2015'
);