计算日期范围

时间:2010-10-22 15:20:08

标签: sql

我正在尝试计算在2009年6月1日之前90天和2009年6月1日之后90天销售的商品,并在下面进行查询。它显示了一些错误。请有人亲切地为我做好准备吗???

SELECT
location,                       
SUM((CASE WHEN t.order_date DATEADD (DAY, -90, '6/1/2009') THEN t.Item ELSE NULL END) as Prior_Items,
SUM(CASE WHEN t.order_date DATEADD (DAY, 89,  '6/1/2009') THEN t.Item ELSE NULL END) as Post_Items
ELSE NULL
END)
FROM mytable t
where date = '6/1/2009'
group by location

2 个答案:

答案 0 :(得分:6)

你的WHEN条件没有正确形成。

CASE WHEN t.order_date DATEADD (DAY, -90, '6/1/2009') THEN t.Item ELSE NULL END
          ^^^^^^^^^^^^^^^^^^^^
很可能你想要的东西是:

CASE WHEN t.order_date>=DATEADD (DAY, -90, '6/1/2009') THEN t.Item ELSE NULL END
                      ^^

答案 1 :(得分:2)

我认为你想要这样的东西。

DECLARE @d DATETIME

SET @d = '20090106'


SELECT
location,                       
SUM(CASE WHEN t.order_date < @d and  t.order_date > DATEADD (DAY, -90, @d) THEN t.Item END) as Prior_Items,
SUM(CASE WHEN t.order_date >=@d AND  t.order_date <  DATEADD (DAY, 89,   @d) THEN t.Item END) as Post_Items
FROM mytable t
where t.order_date BETWEEN  DATEADD (DAY, -90, @d) AND DATEADD (DAY, 89,   @d)
group by location