我有一张包含以下内容的表:
StartDate, EndDate, StartTime, EndTime
我希望能够在每个StartDate:StartTime and EndDate:EndTime
之间生成时间戳。
StartDate 2017-01-01
StartTime 07:20:00
EndDate 2017-01-15
EndTime 15:00:00.
我希望在2017-01-01 07:20和2017-01-01 15:00之间生成每分钟,但是对于2017-01-01和2017-01-15之间的每个日期。 任何帮助将不胜感激。 谢谢
答案 0 :(得分:2)
这将是我今天的第三个答案,建议设置日期维度/日历表。这将使您的生活吨更容易。
答案 1 :(得分:0)
这是你正在寻找的吗?
DECLARE
@StartDate DATE = '2017-01-01',
@StartTime TIME(0) = '07:20:00',
@EndDate DATE = '2017-01-15',
@EndTime TIME(0) = '15:00:00';
DECLARE
@BegDT DATETIME2(0) = CAST(CONCAT(@StartDate, ' ', @StartTime) AS DATETIME2(0)),
@EndDT DATETIME2(0) = CAST(CONCAT(@EndDate, ' ', @EndTime) AS DATETIME2(0));
WITH
cte_n1 (n) AS (SELECT 1 FROM (VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1)) n (n)),
cte_n2 (n) AS (SELECT 1 FROM cte_n1 a CROSS JOIN cte_n1 b),
cte_n3 (n) AS (SELECT 1 FROM cte_n2 a CROSS JOIN cte_n2 b),
cte_Calendar (dt) AS (
SELECT TOP (DATEDIFF(mi, @BegDT, @EndDT) + 1)
DATEADD(mi, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1, @BegDT)
FROM
cte_n3 a CROSS JOIN cte_n3 b
)
SELECT
c.dt
FROM
cte_Calendar c
WHERE
CAST(c.dt AS TIME(0)) BETWEEN @StartTime AND @EndTime;