这是我发布的earlier问题的后续内容。这段代码正是我所询问的内容,但我意识到最终让它工作,我试图做的事实上并不是我所需要的。
DECLARE @StartDateTime datetime = '2015-07-13 14:00:00',
@EndDateTime datetime = '2015-07-13 16:00:00';
WITH JumpsOf15 AS
(
SELECT ROW_NUMBER() OVER(ORDER BY object_id) * 15 AS Step
FROM sys.objects
),
Dates as
(
SELECT currentDate = steppedDate.steppedDate
FROM JumpsOf15
CROSS APPLY(SELECT DATEADD(MINUTE,Step,@StartDateTime) AS steppedDate ) AS steppedDate
WHERE @EndDateTime>steppedDate.steppedDate
)
SELECT d.currentDate, t.Value, t.FK_ConfigId
FROM Dates AS d
OUTER APPLY
( SELECT TOP 1 t.[Timestamp], t.Value, t.FK_ConfigId
FROM myTable AS t
WHERE t.[Timestamp] <= d.currentDate and t.FK_ConfigId in (208812, 208809, 208815)
ORDER BY t.[Timestamp] DESC, t.Value, t.FK_ConfigId
) AS t
这给出了如下输出:
currentDate value FK_ConfigId
1/1/2015 12:15 2 208809
1/1/2015 12:30 5 208815
1/1/2015 12:45 1 208815
但实际上我需要在列表中指定的每个唯一FK_ConfigId
的每个时间戳记录一条记录。现在我每个时间戳只获得一条记录,无论配置ID如何。我想要的输出:
currentDate value FK_ConfigId
1/1/2015 12:15 2 208809
1/1/2015 12:15 4 208815
1/1/2015 12:30 5 208809
1/1/2015 12:30 1 208815
我怎么能实现这个目标?
答案 0 :(得分:0)
试试这个并告诉我你的想法:
DECLARE @StartDateTime datetime = '2015-07-13 14:00:00',
@EndDateTime datetime = '2015-07-13 16:00:00';
WITH JumpsOf15 AS (
SELECT Step = Row_Number() OVER (ORDER BY (SELECT 1)) * 15
FROM sys.objects
),
Dates AS (
SELECT currentDate = DateAdd(minute, Step, @StartDateTime)
FROM JumpsOf15
WHERE Step < DateDiff(minute, 0, @EndDateTime - @StartDateTime)
)
SELECT
d.currentDate,
t.ConfigId,
t.Value
FROM
Dates d
CROSS JOIN (VALUES
(208812), (208809), (208815)
) c (ConfigId)
OUTER APPLY (
SELECT TOP 1
t.[Timestamp],
t.Value,
t.FK_ConfigId
FROM myTable t
WHERE
d.currentDate >= t.[Timestamp]
AND c.ConfigId = t.FK_ConfigId
ORDER BY
t.[Timestamp] DESC,
t.Value
) t
;