我在SQL Server中有一个表,用于存储日期,数据库和事件数(CreateDate
,DB_Name
,Incident
),我可以通过分组到以下内容进行聚合:
[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 :(得分: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