Sql-Server-2008
從查詢中插入缺失日期
如何從我創建的查詢中插入缺失的日期。結果如下:
Date Frequency 2014-05-18 5 2014-05-20 7 2014-05-25 7 2014-05-27 6
我希望結果中缺少 0 值的日期,如下所示:
Date Frequency 2014-05-18 5 2014-05-19 0 2014-05-20 7 2014-05-21 0 2014-05-22 0 2014-05-23 0 2014-05-24 0 2014-05-25 7 2014-05-26 0 2014-05-27 6
請注意,我對伺服器具有隻讀訪問權限。
這是一個使用日曆表的範例(您確實應該擁有)。此範例僅填充 2014 年,但您可以根據需要填充任意年…
CREATE TABLE dbo.Calendar(d DATE PRIMARY KEY); INSERT dbo.Calendar(d) SELECT TOP (365) DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY number)-1, '20140101') FROM [master].dbo.spt_values WHERE [type] = N'P' ORDER BY number;
現在查詢很簡單:
DECLARE @s DATE = '20140518', @e DATE = '20140527'; SELECT c.d, Frequency = COALESCE(s.Frequency,0) FROM dbo.Calendar AS c LEFT OUTER JOIN dbo.splunge AS s ON c.d = s.[date] WHERE c.d >= @s AND c.d < DATEADD(DAY, 1, @e);
如果你不能創建一個日曆表(也沒有一個方便的數字表),那麼你可以把它內聯:
DECLARE @s DATE = '20140518', @e DATE = '20140527'; SELECT c.d, Frequency = COALESCE(s.Frequency,0) FROM ( SELECT TOP (DATEDIFF(DAY, @s, @e)+1) DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY number)-1, @s) FROM [master].dbo.spt_values WHERE [type] = N'P' ORDER BY number ) AS c(d) LEFT OUTER JOIN dbo.splunge2 AS s ON c.d = s.[date] WHERE c.d >= @s AND c.d < DATEADD(DAY, 1, @e);
有關生成集(日期、數字等)的更多資訊,請參閱本系列:
更多關於日曆表: