0

我正在使用SQL Server 2008 R2。我需要得到星期日weekno,並且我已經有了查詢,但它顯示了錯誤的數據。我能做什麼 ?我想要獲得星期日WeekNo?

它顯示了2而不是1。例如,06-JAN-2013(WeekNo - 1)

我的查詢是

SELECT DATEPART (week, '01-13-2013 23:59:59.000') As WeekNo1 , 
    DATEPART (week, '01-06-2013 23:59:59.000') As WeekNo2 , 
    DATEPART (week, '12-30-2012 23:59:59.000') As WeekNo3 , 
    DATEPART (week, '12-23-2012 23:59:59.000') As WeekNo4 , 
    DATEPART (week, '12-16-2012 23:59:59.000') As WeekNo5 , 
    DATEPART (week, '12-09-2012 23:59:59.000') As WeekNo6 

回答

1

查詢:

SQLFIDDLEExample

SET DATEFIRST 1 
SELECT DATEPART (week, '01-13-2013 23:59:59.000') As WeekNo1 , 
     DATEPART (week, '01-06-2013 23:59:59.000') As WeekNo2 , 
     DATEPART (week, '12-30-2012 23:59:59.000') As WeekNo3 , 
     DATEPART (week, '12-23-2012 23:59:59.000') As WeekNo4 , 
     DATEPART (week, '12-16-2012 23:59:59.000') As WeekNo5 , 
     DATEPART (week, '12-09-2012 23:59:59.000') As WeekNo6 

結果:

| WEEKNO1 | WEEKNO2 | WEEKNO3 | WEEKNO4 | WEEKNO5 | WEEKNO6 | 
------------------------------------------------------------- 
|  2 |  1 |  53 |  52 |  51 |  50 | 
+0

初始/原始'DATEFIRST'設置應該在'SELECT ...'後恢復。 –

+0

感謝您的回覆@justin,我接受你的回答.. –

2

您需要將DATEFIRST屬性設置爲星期的開始日期。這指定了一週中的第一天。

要確定您的服務器的一週的第一天是什麼,你將使用:

SELECT @@DATEFIRST 

然後,如果你需要修改的值,你可以使用:

SET DATEFIRST 1; 

SELECT DATEPART (week, '01-13-2013 23:59:59.000') As WeekNo1 , 
    DATEPART (week, '01-06-2013 23:59:59.000') As WeekNo2 , 
    DATEPART (week, '12-30-2012 23:59:59.000') As WeekNo3 , 
    DATEPART (week, '12-23-2012 23:59:59.000') As WeekNo4 , 
    DATEPART (week, '12-16-2012 23:59:59.000') As WeekNo5 , 
    DATEPART (week, '12-09-2012 23:59:59.000') As WeekNo6 

SQL Fiddle with Demo

相關問題