如何从星期六星期六结束的当周开始从sql server获取数据,因此选择本周的星期六到星期五的所有数据。
我发现这个代码但是在星期天开始,我无法改变它:
where Date >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) AND Date < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
在MS Docs上查看SET DATEFIRST。
将一周的第一天设置为1到7之间的数字。
哪里:
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday (default, U.S. English)
看看下一个例子:
DECLARE @CurrentDate DATETIME;
SET @CurrentDate = CONVERT(DATETIME,'2017-01-18');
SET DATEFIRST 1
SELECT DATEADD(day, 1 - DATEPART(dw, @CurrentDate), @CurrentDate);
RETURNS '2017-01-16' (Monday)
SET DATEFIRST 2
SELECT DATEADD(day, 1 - DATEPART(dw, @CurrentDate), @CurrentDate);
RETURNS '2017-01-17' (Tuesday)
SET DATEFIRST 3
SELECT DATEADD(day, 1 - DATEPART(dw, @CurrentDate), @CurrentDate);
RETURNS '2017-01-18' (Wednesday)
SET DATEFIRST 4
SELECT DATEADD(day, 1 - DATEPART(dw, @CurrentDate), @CurrentDate);
RETURNS '2017-01-12' (Thursday)
SET DATEFIRST 5
SELECT DATEADD(day, 1 - DATEPART(dw, @CurrentDate), @CurrentDate);
RETURNS '2017-01-13' (Friday)
SET DATEFIRST 6
SELECT DATEADD(day, 1 - DATEPART(dw, @CurrentDate), @CurrentDate);
RETURNS '2017-01-14' (Saturday)
SET DATEFIRST 7
SELECT DATEADD(day, 1 - DATEPART(dw, @CurrentDate), @CurrentDate);
RETURNS '2017-01-15' (Monday)
你可以在这里查看:http://rextester.com/YSGVM53271
默认情况下,本周将从sunday
开始。要改变它,请使用DATEFIRST
。
SET DATEFIRST 6
WHERE Date >= Cast(Dateadd(dd, -Datepart(WEEKDAY, Getdate()) + 1, Getdate()) AS DATE)
AND Date < Cast(Dateadd(dd, 7 - Datepart(WEEKDAY, Getdate()) + 1, Getdate()) AS DATE)
有关DATEFIRST
的更多信息
+---------------------------+--------------------------+
| Value | First day of the week is |
+---------------------------+--------------------------+
| 1 | Monday |
| 2 | Tuesday |
| 3 | Wednesday |
| 4 | Thursday |
| 5 | Friday |
| 6 | Saturday |
| 7 (default, U.S. English) | Sunday |
+---------------------------+--------------------------+
您可以尝试以下方法。无论SET DATEFIRST
值如何,它都有效:
where [Date] >= CAST(DATEADD(d, -(@@DATEFIRST + DATEPART(dw, GETDATE())) % 7, @d) as DATE)
and [Date] < CAST(DATEADD(d, -(@@DATEFIRST + DATEPART(dw, GETDATE())) % 7 + 6, @d) as DATE)