我在数据库中有如下数据:
+---------------------+-------------+
| CloseTime | Count |
+---------------------+-------------+
| 10.2.2014 13:19 | 1 |
| 5.12.2014 13:19 | 1 |
| 4.2.2014 13:19 | 1 |
| 2.1.2014 13:19 | 1 |
| 4.12.2014 13:19 | 1 |
+---------------------+-------------+
现在,我有这样的查询
SELECT DATENAME(MONTH, CLOSETIME) AS CLOSEMONTH, COUNT(*) as CNT
FROM TABLE
WHERE CLOSETIME >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE())-7, '19000101')
AND CLOSETIME < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101')
GROUP BY DATENAME(MONTH, CLOSETIME);
导致
+---------------+-------+
| CloseTime | CNT |
+---------------+-------+
| February | 2 |
| January | 1 |
| December | 2 |
+---------------+-------+
查询的工作方式是过去7个月的数据。我需要结果
+---------------+-------+
| CloseTime | Count |
+---------------+-------+
| February | 2 |
| January | 1 |
| December | 2 |
| November | 0 |
| October | 0 |
| September | 0 |
| August | 0 |
+---------------+-------+
因此,如果在以后的几个月内没有关闭时间的记录,它仍应返回零计数的月份。怎么做到这一点?我更喜欢SQL解决方案,这意味着没有程序或脚本。
我试过
SELECT DATENAME(MONTH,DATEADD(MONTH,-1,GETDATE())) as HELP_MONTH
UNION ALL
...
然后加入它,但它没有成功。
答案 0 :(得分:0)
通过添加HAVING子句使用相同的查询将添加具有0计数的记录。
SELECT DATENAME(MONTH, CLOSETIME) AS CLOSEMONTH, COUNT(*) as CNT
FROM TABLE
WHERE CLOSETIME >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE())-7, '19000101')
AND CLOSETIME < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101')
GROUP BY DATENAME(MONTH, CLOSETIME)
HAVING COUNT(*) >= 0
感谢。
答案 1 :(得分:0)
以下查询可以使用您的结果集进行LEFT JOIN
:
SELECT * FROM
(
SELECT 'January' AS month_name, 1 AS month_num
UNION
SELECT 'February',2
UNION
SELECT 'Mar',3
UNION
SELECT 'Apr',4
UNION
SELECT 'May',5
UNION
SELECT 'June',6
UNION
SELECT 'July',7
UNION
SELECT 'August', 8
UNION
SELECT 'September', 9
UNION
SELECT 'October', 10
UNION
SELECT 'November', 11
UNION
SELECT 'December', 12
)
months
WHERE month_num <= MONTH(GETDATE())
OR month_num > (MONTH(GETDATE()) - 7) % 12 + 12
以上查询给出了结果集的最后7个月:
以下是SQL Fiddle
的代码答案 2 :(得分:0)
好的,这对我有用:
WITH HM (HELP_MONTH) AS (
SELECT DATENAME(MONTH,DATEADD(MONTH,-1,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-2,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-3,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-4,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-5,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-6,GETDATE())) AS HELP_MONTH
UNION ALL
SELECT DATENAME(MONTH,DATEADD(MONTH,-7,GETDATE())) AS HELP_MONTH)
SELECT HELP_MONTH
,COUNT(CNT) AS CNT
FROM HM
LEFT JOIN YOUR_TABLE ON HM.HELP_MONTH = DATENAME(MONTH, CLOSETIME)
AND CLOSETIME >= DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE())-7, '19000101')
AND CLOSETIME < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()), '19000101')
GROUP BY DATENAME(MONTH, CLOSETIME), HELP_MONTH