SQL Sum和Count按月分隔

时间:2015-12-05 15:49:04

标签: sql sql-server sql-server-2008

我正在编写一个查询表的脚本,并计算状态为10的所有行,并按月分隔总计数。有点儿 不正确的考虑我的结果中有两个Decembers。

11月,只有一个日期,意味着两行的状态为10,并且在同一日期(11-04)。 12月在同一日期(12-04)有252行,1行有12-05日期。

如何按月查询和分隔计数和日期?

非常感谢任何帮助。

SELECT CONVERT(CHAR(3), Datename(month, datecomplete)) AS Month, 
       Count(*)                                        AS Val 
FROM   nwds 
WHERE  status = 10 
GROUP  BY Datediff(month, 0, datecomplete), 
          datecomplete 

我的结果

Nov 2
Dec 252
Dec 1

期望的结果

Nov 2
Dec 253

3 个答案:

答案 0 :(得分:1)

datecomplete应从group by中排除,否则结果将按天分组。分组需要位于datecomplete列的monthyear部分。

SELECT 
CONVERT(CHAR(3), Datename(month, datecomplete)) AS Month, 
count(*)  AS Val 
FROM   nwds 
WHERE  status = 10 
GROUP  BY CONVERT(CHAR(3), Datename(month, datecomplete)) ,
datepart(yyyy, datecomplete)

答案 1 :(得分:1)

SELECT LEFT(DATENAME(M, datecomplete), 3) AS Month, 
       Count(*)                           AS Val 
FROM   nwds 
WHERE  status = 10 
GROUP  BY LEFT(DATENAME(M, datecomplete), 3)

如果您获得了不同年份的数据,可以将年份添加到GROUP BY

SELECT LEFT(DATENAME(M, datecomplete), 3) AS Month, 
       YEAR(datecomplete)                 AS Year,
       Count(*)                           AS Val 
FROM   nwds 
WHERE  status = 10 
GROUP  BY LEFT(DATENAME(M, datecomplete), 3), YEAR(datecomplete)

答案 2 :(得分:1)

试试这个

select CONVERT(char(3),DATENAME(MONTH,datecomplete)) as [month],
       count(*)                                      as val
from nwds
WHERE  status = 10 
group by CONVERT(char(3),DATENAME(MONTH,datecomplete))