我首先想到的是通过查看一年中的哪一天来填补缺失的日期。您可以通过加入主数据库中的 spt_values 表并将数字添加到一年的第一天来做到这一点。
DECLARE @Table AS TABLE(ADate Date, ANumber Int);
INSERT INTO @Table
VALUES
('2013-11-01',12),
('2013-11-12',15),
('2013-11-21',13),
('2013-12-01',0);
SELECT
DateAdd(D, v.number, MinDate) Date
FROM (SELECT number FROM master.dbo.spt_values WHERE name IS NULL) v
INNER JOIN (
SELECT
Min(ADate) MinDate
,DateDiff(D, Min(ADate), Max(ADate)) DaysInSpan
,Year(Min(ADate)) StartYear
FROM @Table
) dates ON v.number BETWEEN 0 AND DaysInSpan - 1
接下来我将把它包装成一个派生表,并添加一个子查询来获取最新的数字。您的最终结果可能类似于:
DECLARE @Table AS TABLE(ADate Date, ANumber Int);
INSERT INTO @Table
VALUES
('2013-11-01',12),
('2013-11-12',15),
('2013-11-21',13),
('2013-12-01',0);
-- Uncomment the following line to see how it behaves when the date range spans a year end
--UPDATE @Table SET ADate = DateAdd(d, 45, ADate)
SELECT
AllDates.Date
,(SELECT TOP 1 ANumber FROM @Table t WHERE t.ADate <= AllDates.Date ORDER BY ADate DESC)
FROM (
SELECT
DateAdd(D, v.number, MinDate) Date
FROM
(SELECT number FROM master.dbo.spt_values WHERE name IS NULL) v
INNER JOIN (
SELECT
Min(ADate) MinDate
,DateDiff(D, Min(ADate), Max(ADate)) DaysInSpan
,Year(Min(ADate)) StartYear
FROM @Table
) dates ON v.number BETWEEN 0 AND DaysInSpan - 1
) AllDates