如何从星期六星期六结束的当周开始从sql server获取数据,所以选择本周的星期六到星期五的所有数据。
我找到了这段代码,但是在周日开始,我无法改变它:
where Date >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) AND Date < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate()))
答案 0 :(得分:4)
在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
答案 1 :(得分:1)
默认情况下,周将从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 |
+---------------------------+--------------------------+
答案 2 :(得分:0)
您可以尝试以下操作。无论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)
答案 3 :(得分:0)
尝试这个例子
SELECT count(AddTime) AS time,
CASE
WHEN (weekday(AddTime)<=3) THEN date(AddTime + INTERVAL (3-weekday(AddTime)) DAY)
ELSE date(AddTime + INTERVAL (3+7-weekday(AddTime)) DAY)
END AS week_days
FROM SAAS_Appoint
WHERE Status = 2
AND AddTime > "2020-01-01 00:00:00"
GROUP BY week_days;
$ weekArr = array('Monday'=> 0,'Tuesday'=> 1,'Wednesday'=> 2,'Thursday'=> 3,'Friday'=> 4,'周六'=> 5, 'Sunday'=> 6);
示例从星期五开始,到今天结束。 只需将3替换为您喜欢的任何一天。