你的第一次嘗試似乎相當接近,我想你的功能只需要將1移到模函數的外部即可。這個工作對我來說:
SELECT DATEADD(DAY, -1 - ((DATEPART(WEEKDAY, GETDATE()) + @@DATEFIRST) % 7), CAST(GETDATE() AS DATE));
然後在一個更大的樣本測試,它似乎仍然工作:
DECLARE @T TABLE (DateFirst INT, Date DATE, LastFriday DATE)
DECLARE @I INT = 1;
WHILE @I < 8
BEGIN
SET DATEFIRST @i;
WITH TestDates AS
( SELECT Date = DATEADD(DAY, -Number, CAST(GETDATE() AS DATE))
FROM master..spt_values
WHERE Type = 'P'
AND Number BETWEEN 0 AND 20
)
INSERT @T (DateFirst, Date, lastFriday)
SELECT @I,
Date,
LastFriday = DATEADD(DAY, -1 - ((DATEPART(WEEKDAY, Date) + @@DATEFIRST) % 7), Date)
FROM TestDates;
SET @i += 1;
END
SELECT *
FROM @T
PIVOT
( MAX(LastFriday)
FOR DateFirst IN ([1], [2], [3], [4], [5], [6], [7])
) pvt
ORDER BY Date;
這適用於所有的語言和DATEFIRST設置。
如果你能控制你的DATEFIRST設置這個變得更簡單:
SET DATEFIRST 6;
SELECT DATEADD(DAY, -DATEPART(WEEKDAY, GETDATE()), CAST(GETDATE() AS DATE))
不過我總是建議讓您的查詢對本地設置安全。
我猜這是[標籤:SQL服務器]? – Mureinik
是的,我已經更新 – VeecoTech