因此,您确实需要能够处理一些 CASE 语句来处理所有边缘情况。这是我放在一起的一个例子。Numbers 表只是一个计数表,在本例中为 1 到 30。
CREATE TABLE #times (id INT IDENTITY(1,1), start_stamp DATETIME, end_stamp DATETIME)
INSERT INTO #times
(
start_stamp ,
end_stamp
)
SELECT DATEADD(DAY, -2*Number, CURRENT_TIMESTAMP), DATEADD(DAY, -1*Number, CURRENT_TIMESTAMP)
FROM Common.NUMBERS
WHERE Number < 31
SELECT id, start_stamp, end_stamp,
CASE WHEN DATEDIFF(DAY, start_stamp, end_stamp) < 7 THEN
CASE WHEN DATEPART(weekday, start_stamp) < DATEPART(weekday, end_stamp)
THEN DATEDIFF(MINUTE, start_stamp, DATEADD(HOUR, -48, end_stamp))
ELSE DATEDIFF(MINUTE, start_stamp, end_stamp) END
ELSE DATEDIFF(MINUTE, start_stamp, DATEADD(HOUR, -48*(DATEDIFF(WEEK, start_stamp, end_stamp)), end_stamp)) END
+ CASE WHEN DATENAME(weekday,start_stamp) IN ('Sunday', 'Saturday') THEN 1440 ELSE 0 END
+ CASE WHEN DATENAME(weekday,end_stamp) IN ('Sunday', 'Saturday') THEN 1440 ELSE 0 END
FROM #times
可能有一种更优雅的方法可以做到这一点,但代码允许您针对整个结果集运行并按行计算。