2014-03-12 63 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