您需要一个表作为缺失日期和天数的查找表,以覆盖查询结果中的日期范围。您可以像这样创建一个:
-- add a temp table for your sample data
CREATE TABLE #Results
([Date] datetime, [Day] int, [Sale Qty] int, [Purchase Qty] int, [Transfer Qty] int)
;
-- insert your sample data
INSERT INTO #Results
([Date], [Day], [Sale Qty], [Purchase Qty], [Transfer Qty])
VALUES
('2015-04-05 00:00:00', 1, 11, 0, 0),
('2015-04-07 00:00:00', 3, 0, 16, 0),
('2015-04-08 00:00:00', 4, 12, 14, 17),
('2015-04-11 00:00:00', 7, 1, 2, 0)
;
-- find the max date
DECLARE @MaxDate DATETIME = (SELECT TOP 1 [Date] FROM #Results ORDER BY [Date] DESC)
-- recursive cte to build the date & day lookup table
;WITH cte AS (
-- cte anchor is the min date and day = 1
SELECT MIN([Date]) AS DateValue, 1 AS [Day]
FROM #Results
UNION ALL
-- uses dateadd to increment days until @MaxDate reached
SELECT DATEADD(DAY, 1, cte.DateValue), [Day] +1
FROM cte
WHERE DATEADD(DAY, 1, cte.DateValue) <= @MaxDate
)
-- inserts values into temp lookup table
SELECT *
INTO #DateLookup
FROM cte
这将创建一个临时表,其中包含使用保存这些值的结果中的最低和最高日期的值范围:
DateValue Day
----------------------------
2015-04-05 00:00:00.000 1
2015-04-06 00:00:00.000 2
2015-04-07 00:00:00.000 3
2015-04-08 00:00:00.000 4
2015-04-09 00:00:00.000 5
2015-04-10 00:00:00.000 6
2015-04-11 00:00:00.000 7
然后,您需要链接到该表并替换任何NULL
价值观与0
像这样:
SELECT #DateLookup.[DateValue] AS [Date],
#DateLookup.[Day] ,
COALESCE([Sale Qty],0) AS [Sale Qty],
COALESCE([Purchase Qty],0) AS [Purchase Qty],
COALESCE([Transfer Qty],0) AS [Transfer Qty]
FROM #DateLookup
LEFT JOIN #Results ON #DateLookup.DateValue = #Results.[Date]
-- some tidy up
DROP TABLE #Results
DROP TABLE #DateLookup