2015-09-30 65 views
1

無論日期如何,我都需要在五個單獨列表中加載最近五週的信息。所以本週,我需要在此之前的最後5周。下一週,我需要在這之前的最後5周,其中包括這一個。如果這是有道理的,不會讓你感到困惑?獲取最近5周的範圍

所以基本上:

..BETWEEN '2015-09-21' AND '2015-09-27' 

不得不被替換爲:

SELECT DATEADD(wk,DATEDIFF(wk,7,GETDATE()),0) AND DATEADD(wk,DATEDIFF(wk,7,GETDATE()),6) 

這只是正常,同爲第二週:

SELECT DATEADD(wk,DATEDIFF(wk,14,GETDATE()),0) AND DATEADD(wk,DATEDIFF(wk,14,GETDATE()),6) 

從那時上,它不再工作。我得到不同的結果比手動添加日期。

SELECT DATEADD(wk,DATEDIFF(wk,21,GETDATE()),0) AND DATEADD(wk,DATEDIFF(wk,21,GETDATE()),6) 

我在做我的代碼錯了嗎?

+0

年底大概你正在使用SQL Server。你應該這樣標記問題。 –

+0

檢查此鏈接將有助於:http://stackoverflow.com/questions/6089960/mysql-query-to-select-data-from-last-week – soorapadman

+0

你會得到什麼結果?查詢'SELECT DATEADD(wk,DATEDIFF(wk,21,GETDATE()),0),DATEADD(wk,DATEDIFF(wk,21,GETDATE()),6)'返回一些意想不到的事情嗎? –

回答

1

如果使用BETWEENdatetime數據類型,你應該天添加到本週初發現周

DATEADD(wk,DATEDIFF(wk,21,GETDATE()),7) 
1

我想你可以使用,而不是手動設置number類似的代碼:

DECLARE @TestDate AS DATETIME 
DECLARE @WeekNumber AS INTEGER 

-- previous 5 weeks 
SELECT @TestDate = GETDATE() 
SELECT @WeekNumber = -5 

WHILE @WeekNumber < 0 
BEGIN 

    SELECT @TestDate, 
     @WeekNumber, 
     DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 0) AS StartDate, 
     DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 6) AS EndDate 

    SELECT @WeekNumber = @WeekNumber + 1 

END 

-- previous 5 weeks from next wednesday 
SELECT @TestDate = DATEADD(DAY, 7, GETDATE()) 
SELECT @WeekNumber = -5 

WHILE @WeekNumber < 0 
BEGIN 

    SELECT @TestDate, 
     @WeekNumber, 
     DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 0) AS StartDate, 
     DATEADD(WEEK, DATEDIFF(WEEK, 0, DATEADD(WEEK, @WeekNumber, @TestDate)), 6) AS EndDate 

    SELECT @WeekNumber = @WeekNumber + 1 

END 

請注意:WHILE循環的內容不會改變。我使用相同的代碼來提取有關兩個不同日期的信息。

相關問題