2017-01-18 72 views
0

如何從本週的星期六開始的當前周從sql server獲取數據,因此請選擇本週從週六到週五的所有數據。如何獲取當前星期的數據週五從SQL服務器開始週末結束

我發現這個代碼,但在週日開始,我不能改變它:

where Date >= dateadd(day, 1-datepart(dw, getdate()), CONVERT(date,getdate())) AND Date < dateadd(day, 8-datepart(dw, getdate()), CONVERT(date,getdate())) 

回答

3

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) 

更多信息以在MS文檔看看SET DATEFIRST

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) 

至7

哪裏設置一週的第一天,從1-10的數你可以在這裏查看:http://rextester.com/YSGVM53271

+0

您好,感謝您的回答,其實應該從數字0到7, 編輯你的答案,使其答案。 –

+0

你確定它運行0-7嗎?那會提示8種不同的設置 - 0做什麼?也許它做了一些事情 - 但無論如何,你不需要它,因爲答案涵蓋了所有的日子。 – Cato

+0

如果我把它形式1第一個星期六沒有顯示,請如果你可以嘗試它嘗試並告訴我 –

1

默認情況下,本週將開始sunday。要更改它,請使用DATEFIRST。在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     | 
+---------------------------+--------------------------+ 
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) 
+0

什麼是列名@d ?? –

相關問題