如何从SQL Server获取一年中每个月的计数记录?

时间:2017-05-23 13:11:44

标签: sql sql-server

我尝试了这段代码,它返回了所有带有月份名称但没有总计数的记录

SELECT 
    DATENAME(month, DATEADD(month, MONTH([R_datetime]), -1 )) MonName,
    COUNT(*) count 
FROM 
    [Tbl_TechRequest]
WHERE 
    ([R_datetime]) BETWEEN DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) 
                       AND DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1)    
GROUP BY  
    [R_datetime] 

1 个答案:

答案 0 :(得分:0)

SELECT 
    DATEPART(year, R_datetme),
    DATEPART(month, R_datetime),
    count (*) 
from myTable
where
    [R_datetime])  > = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) 
group by 
    DATEPART(year, R_datetme), 
    DATEPART(month, R_datetime)

OR

SELECT
    DATEPART(year, R_datetme)*100 + DATEPART(month, R_datetime),
    count(*) 
from myTable
where
    [R_datetime])  > = DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) + 1, -1) 
group by 
    DATEPART(year, R_datetme)*100 + DATEPART(month, R_datetime)