我正在尝试使用SELECT从SQL Server显示计数和组

bvjxkvbb  于 2022-11-21  发布在  SQL Server
关注(0)|答案(1)|浏览(125)

我尝试使用SQL Server中的Group By显示每月和每年的OS和部门数量:

SELECT 
    COUNT(EVT_CODE) AS OS, EVT_MRC AS DEPARTMENT, 
    DATENAME(MONTH, EVT_CREATED) AS MONTH, 
    YEAR(EVT_CREATED) AS YEAR
FROM
    R5EVENTS
GROUP BY 
    EVT_MRC, YEAR(EVT_CREATED), DATENAME(MONTH, EVT_CREATED)
ORDER BY 
    'YEAR' DESC

我预料到了这些结果:

ugmeyewa

ugmeyewa1#

我认为您希望对表进行枢轴旋转,以便月份是列名。下面的代码示例没有经过测试,因为您没有提供示例数据。

SELECT 
    COUNT(EVT_CODE) AS OS, EVT_MRC AS DEPARTMENT, 
    DATENAME(MONTH, EVT_CREATED) AS MONTH, 
    YEAR(EVT_CREATED) AS YEAR
FROM
    R5EVENTS
PIVOT  
(  
    COUNT(EVT_CODE) 
FOR [MONTH] IN
    January, February, March, April, May, June, August, September, October, November, December
) AS p 
GROUP BY 
    EVT_MRC, YEAR(EVT_CREATED), DATENAME(MONTH, EVT_CREATED)
ORDER BY 
    'YEAR' DESC

相关问题