您需要使用遞歸CTE。我假設datetime的列被稱爲ChangedDate
,在你的問題的第二列中的值爲SomeValue
。
;WITH cte AS (
SELECT t.ChangedDate,
t.SomeValue,
p.ChangedDate as NextDate
FROM YourTable t
OUTER APPLY (
SELECT top 1 *
FROM YourTable
WHERE t.ChangedDate <ChangedDate
ORDER BY ChangedDate
) p
UNION ALL
SELECT DATEADD(minute,1,ChangedDate),
SomeValue,
NextDate
FROM cte
WHERE DATEADD(minute,1,ChangedDate) < NextDate
)
SELECT ChangedDate,
SomeValue
FROM cte
ORDER BY ChangedDate
OPTION (MAXRECURSION 0)
爲您的樣品將輸出:
ChangedDate SomeValue
2016-09-05 09:50:24.000 20
2016-09-05 09:51:24.000 20
2016-09-05 09:52:24.000 20
2016-09-05 09:53:24.000 20
2016-09-05 09:54:24.000 20
2016-09-05 09:55:24.000 20
2016-09-05 09:56:14.000 18
如果你添加一個字符串像('2016-09-05 10:00:34', 17)
,它將輸出:
ChangedDate SomeValue
2016-09-05 09:50:24.000 20
2016-09-05 09:51:24.000 20
2016-09-05 09:52:24.000 20
2016-09-05 09:53:24.000 20
2016-09-05 09:54:24.000 20
2016-09-05 09:55:24.000 20
2016-09-05 09:56:14.000 18
2016-09-05 09:57:14.000 18
2016-09-05 09:58:14.000 18
2016-09-05 09:59:14.000 18
2016-09-05 10:00:14.000 18
2016-09-05 10:00:34.000 17
如果需要此日誌持續到現在時間改變這部分:
p.ChangedDate as NextDate
在CTE在此:
這裏
COALESCE(p.ChangedDate,GETDATE()) as NextDate
一個辦法是有,你用它來填補丟失的數據的日期/時間表。 –