我從這個社區找到了很多幫助。我想把最後的SQL腳本放在這裏供其他人使用。
WITH cte ([VID],[StartTime],[EndTime]) AS
(SELECT tbl.[ID] as 'VID'
,CONVERT(VARCHAR(19), tbl.[StartDT], 120) AS 'StartTime'
,CASE
WHEN tbl.[EndDT] <= CONVERT(VARCHAR(11), tbl.[StartDT]+1, 120) + '00:00:00' THEN CONVERT(VARCHAR(19), tbl.[EndDT], 120)
ELSE CONVERT(VARCHAR(11), tbl.[StartDT]+1, 120) + '00:00:00'
END as 'EndTime'
FROM [SourceTable] as tbl
WHERE DATEDIFF(DAY,tbl.[StartDT],tbl.[EndDT])<=365
UNION ALL
SELECT tbl.[ID] as 'VID'
,CONVERT(VARCHAR(11), DATEADD(DAY, 1, cte.[StartTime]), 120) + '00:00:00' AS 'StartTime'
,CASE
WHEN CONVERT(VARCHAR(19), tbl.[EndDT], 120) < CONVERT(VARCHAR(11), DATEADD(DAY, 2, cte.[StartTime]), 120) + '00:00:00'
THEN CONVERT(VARCHAR(19), tbl.[EndDT], 120)
ELSE CONVERT(VARCHAR(11), DATEADD(DAY, 2, cte.[StartTime]), 120) + '00:00:00'
END AS 'EndTime'
FROM cte
INNER JOIN [SourceTable] as tbl
ON cte.VID = tbl.ID
WHERE CONVERT(VARCHAR(11), cte.[StartTime], 120) < CONVERT(VARCHAR(11), tbl.[EndDT], 120))
SELECT VID AS ID
,[StartTime]
,[EndTime]
,DateDiff (second,[StartTime],[EndTime])/3600 As 'Hours'
,DateDiff (second,[StartTime],[EndTime])/60 % 60 as 'Minutes'
,((DateDiff (Second,[StartTime],[EndTime])/3600)*60)+(DateDiff (second,starttime,endtime)/60 % 60) as 'Total Minutes'
,DATEPART(week,[StartTime]) AS weeknum
,MONTH([StartTime]) AS MonthNumber
,DATENAME(month,[StartTime]) AS MonthName
FROM cte order by Id, [StartTime]
option (maxrecursion 0);
標記您正在使用的dbms,您已經有一個產品特定的答案。 – jarlh
添加一些示例表數據和預期結果。同時向我們展示您當前的查詢嘗試。 – jarlh
[如何在SQL Server中生成一系列日期]的可能重複(https://stackoverflow.com/questions/11141507/how-to-generate-a-range-of-dates-in-sql-server) – McNets