我的任务是创建一个报告,该报告应该显示我们环境中过去12个月中每个月的不同操作系统类型的SQL Server。
我创建了下表,每天都在里面加载数据:
我需要以过去12个月的每个月的操作系统类型以下列格式显示:
我编写了以下查询,但这是错误的。我的斗争是如何让每个月的最后一个数据集合(不是每个月的最后一天)计算操作系统类型,并以格式Mon YYYY
显示日期。我使用SQL Server 2008 R2。有什么想法吗?
WITH cte AS (
SELECT OSVer = CASE OSVer
WHEN '5.0.2195' THEN 'Windows Server 2000'
WHEN '5.2.3790' THEN 'Windows Server 2003'
WHEN '6.0.6002' THEN 'Windows Server 2008'
WHEN '6.1.7600' THEN 'Windows Server 2008 R2'
WHEN '6.1.7601' THEN 'Windows Server 2008 R2 SP1'
WHEN '6.2.9200' THEN 'Windows Server 2012'
WHEN '6.3.9600' THEN 'Windows Server 2012 R2'
ELSE OSVer
END,
Date,
ROW_NUMBER() OVER (PARTITION BY DATEDIFF(DAY, 0, Date) ORDER BY Date DESC) as rn
FROM dbo.SQLMachines
WHERE OSName IS NOT NULL
)
SELECT OSVer, Count(OSVer) AS 'Count', Date
FROM cte
where rn = 1
GROUP BY OSVer, Date
ORDER BY Date DESC
答案 0 :(得分:0)
使用窗口函数获取每个月的数据的最后一天,并使用它来选择适当的行:
WITH cte AS (
SELECT OSVer = CASE OSVer
WHEN '5.0.2195' THEN 'Windows Server 2000'
WHEN '5.2.3790' THEN 'Windows Server 2003'
WHEN '6.0.6002' THEN 'Windows Server 2008'
WHEN '6.1.7600' THEN 'Windows Server 2008 R2'
WHEN '6.1.7601' THEN 'Windows Server 2008 R2 SP1'
WHEN '6.2.9200' THEN 'Windows Server 2012'
WHEN '6.3.9600' THEN 'Windows Server 2012 R2'
ELSE OSVer
END,
Date,
MAX(Date) OVER (PARTITION BY YEAR(Date), MONTH(Date)) as maxDay
FROM dbo.SQLMachines
WHERE OSName IS NOT NULL
)
SELECT OSVer, Count(OSVer) AS cnt, CAST(Date a Date)
FROM cte
WHERE CAST(Date as Date) = CAST(MaxDay as Date)
GROUP BY OSVer, CAST(Date a Date)
ORDER BY CAST(Date as Date) DESC;
只有cast()
有时间组件时才需要Date
。