2014-03-12 89 views
0

我在SQL Server中的表存儲日期,db和事件的數量(CreateDateDB_NameIncident),我可以通過分組到類似下面的聚合:一組填補空白的查詢

[CreateDate] [DB_Name] [Count of Incidents] 
20140214  tempdb  10 
20140215  tempdb  9 
20140217  tempdb  8 
20140215  msdb   10  
20140218  msdb   11 

但想(用於圖形和數據)這樣的:

[CreateDate] [DB_Name] [Count of Incidents] 
20140214  tempdb  10 
20140215  tempdb  9 
20140216  tempdb  0 
20140217  tempdb  8 
20140218  tempdb  0 
20140214  msdb   0  
20140215  msdb   10  
20140216  msdb   0  
20140217  msdb   0  
20140218  msdb   11 

我願把這個視圖。我試過CTE,但沒有看過「適用」。

歡呼和感謝您的幫助/建議。

+0

應該有一個CRLF來分成兩個lines20140217 tempdb的8 20140218 tempdb的這個0 –

+2

你只需要使用一個日曆表和區議會的查找表,然後'LEFT JOIN'您計數 – JNK

+2

你有日曆表? –

回答

0

我同意日曆表可以讓你的生活變得更容易的評論,因爲它可以用於數據庫的多種用途,但是如果你想僅使用提供的信息創建一個視圖,那麼遞歸CTE解。

/* 
--  Create Base Table 
If  Object_ID('GappedHistory') Is Not Null Drop Table GappedHistory; 
Create Table GappedHistory (CreateDate Date, DBName Varchar(50), CntOfIncidents Int); 
Insert GappedHistory (CreateDate, DBName, CntOfIncidents) 
Values ('2014-02-14', 'tempdb', 10), 
     ('2014-02-15', 'tempdb', 9), 
     ('2014-02-17', 'tempdb', 8), 
     ('2014-02-15', 'msdb', 10), 
     ('2014-02-18', 'msdb', 11); 
Go 
*/ 

--  Build the view 
Create View vwAllDatesResults 
As 
With dates As 
(
     Select Distinct 
       DBName, 
       Min(CreateDate) Over (Order By CreateDate) As rangeDates, 
       Max(CreateDate) Over (Order By CreateDate Desc) As maxCreateDate 
     From GappedHistory g 
     Union All 
     Select DBName, 
       DateAdd(Day,1,rangeDates), 
       maxCreateDate 
     From dates 
     Where rangeDates < maxCreateDate  
),  recurCTE As 
(
     Select IsNull(g.CreateDate, m.rangeDates) As CreateDate, 
       IsNull(g.DBName, m.DBName) As DBName, 
       IsNull(g.CntOfIncidents,0) As CntOfIncidents 
     From GappedHistory g 
     Full Outer Join dates m 
       On g.CreateDate = m.rangeDates 
       And g.DBName = m.DBName 
) 
Select * 
From recurCTE 
Go 

--  Query the view 
Select * 
From vwAllDatesResults 
Order By DBName Desc, CreateDate