2012-08-14 65 views
1

我沒能獲得在weekwise算IE 7日內發貨訂單爲一週,請查看我的查詢,如下所示:如何獲得最近5周從用戶輸入的日期數據的

Declare @CurrentDate nvarchar(50); 
SET @CurrentDate='2012-07-25' 

BEGIN 

;WITH DateList AS 
(
    SELECT DATEADD(WEEK, 0, CONVERT(DATETIME, @CurrentDate)) AS CreateDateTime, 1 AS Cnter 
    UNION ALL 
    SELECT DATEADD(WEEK, -1, CreateDateTime), DateList.Cnter + 1 
    FROM DateList 
    WHERE DateList.Cnter < 5 
) 
SELECT DateList.CreateDateTime AS ShipWeek, COALESCE(Temp.TotalCount, 0) AS TotalCount 
FROM DateList 
LEFT JOIN 
(
    SELECT COUNT(Id) TotalCount 
     ,DATEADD(WEEK, DATEDIFF(WEEK, '19000101',CreatedDateTime),'19000101') AS ShipWeek 
    FROM ShipmentDetail 
    WHERE CreatedDateTime 
    BETWEEN DATEADD(DAY,-30,@CurrentDate) AND @CurrentDate 
    GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, '19000101',CreatedDateTime),'19000101') 
) Temp 
    ON CONVERT(VARCHAR(10), DateList.CreateDateTime, 112) = Temp.ShipWeek 
END 

結果表如下:

ShipWeek    TotalCount 
2012-07-25 00:00:00.000 0 
2012-07-18 00:00:00.000 0 
2012-07-11 00:00:00.000 0 
2012-07-04 00:00:00.000 0 
2012-06-27 00:00:00.000 0 

請給我確切的解決方案。

如果我輸入當前日期,如:

SET @CurrentDate='2012-07-30' 

那麼結果表會給喜歡數據:

ShipWeek    TotalCount 
2012-07-30 00:00:00.000 0 
2012-07-23 00:00:00.000 1406 
2012-07-16 00:00:00.000 0 
2012-07-09 00:00:00.000 0 
2012-07-02 00:00:00.000 0 

爲什麼我如果我輸入當前日期像'2012-07-27'

回答

2

我沒有得到如果使用範圍而不是截斷日期來精確度,它會變得更容易。我已經改變了cte來生成範圍並刪除了派生表。現在查詢可能會使用索引。哦,而且我不確定將CreatedDateTime縮短到最近30天的附加條件 - 第一週將失去一些貨件。

Declare @CurrentDate datetime 
SET @CurrentDate='2012-07-25' 
;WITH DateList AS 
(
    SELECT DATEADD(WEEK, 0, CONVERT(DATETIME, @CurrentDate)) AS StartRange, 
      DATEADD(WEEK, 1, CONVERT(DATETIME, @CurrentDate)) AS EndRange, 
      1 AS Cnter 
    UNION ALL 
    SELECT DATEADD(WEEK, -1, StartRange), 
      DATEADD(WEEK, -1, EndRange), 
      DateList.Cnter + 1 
    FROM DateList 
    WHERE DateList.Cnter < 5 
) 
SELECT DateList.StartRange AS ShipWeek, 
     COALESCE(count(ShipmentDetail.CreatedDateTime), 0) AS TotalCount 
FROM DateList 
LEFT JOIN ShipmentDetail 
    ON DateList.StartRange <= ShipmentDetail.CreatedDateTime 
    AND DateList.EndRange > ShipmentDetail.CreatedDateTime 
    AND ShipmentDetail.CreatedDateTime 
     BETWEEN DATEADD(DAY,-30,@CurrentDate) 
        AND @CurrentDate 
GROUP BY DateList.StartRange; 

Sql Fiddle with example is this way

+0

+1 Nice ans幫了我:) – RajeshKdev 2014-04-24 10:21:53

相關問題