2016-07-19 85 views
1

我有創建報告的任務,該報告應顯示過去12個月中每個月的環境中SQL Server的不同操作系統類型。過去12個月中每個月的SQL Server操作系統類型數

我創建了下面的表格和數據加載每天裏面: enter image description here

我需要得到操作系統類型每個月要顯示在下面的格式過去12個月: enter image description here

我寫了下面的查詢,但它是錯誤的。我的掙扎是如何獲得每月最後一次數據收集(不是每個月的最後一天)的操作系統類型計數,並以格式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

使用窗函數得到最後一天,每個月的數據,並用它來選擇相應的行:如果Date有一個時間組件時,才需要

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()秒。

+0

工作正常!謝謝! –

相關問題