如何从用户输入日期获取最近5周的数据

时间:2012-08-14 10:14:37

标签: sql-server

我无法按周计算,即7天发货订单为一周,请按以下方式检查我的查询:

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'

之类的当前日期,为什么我没有收到

1 个答案:

答案 0 :(得分: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