Teradata - 按日期范围分组

时间:2013-06-11 18:01:58

标签: sql teradata

我有这种情况,其中必须汇总属于特定日期范围(每7天)的每个项目的采购订单。

ITEM_NUMBER  ORDERED_DATE  ORDER_QUANTITY
1            06/01/2013    5
1            06/02/2013    12
1            06/03/2013    3
1            06/06/2013    8
1            06/18/2013    7
1            06/21/2013    9
1            06/29/2013    3
1            06/30/2013    4

2            06/03/2013    24
2            06/07/2013    1
2            06/19/2013    22
2            06/23/2013    12
2            06/30/2013    9

上述记录必须汇总到7天窗口,关于ITEM,如下所示

Item 1 - Orders from 06/01/2013 to 06/07/2013 as one group (7 days)
Item 1 - Orders from 06/18/2013 to 06/24/2013 as second group (7 days)
Item 1 - Orders from 06/29/2013 to 07/05/2013 as third group (7 days)
Item 2 - Orders from 06/03/2013 to 07/09/2013 as forth group (7 days) and so on

因此最终输出应为

ITEM_NUMBER  MIN(ORDERED_DATE)  SUM(ORDER_QUANTITY)
1            06/01/2013         28
1            06/18/2013         16
1            06/29/2013         7

2            06/03/2013         25
2            06/19/2013         34
2            06/30/2013         9

如果这是重复,请道歉。 提前谢谢!

1 个答案:

答案 0 :(得分:1)

以下是一种可能的解决方案:

select  a.ITEM_NUMBER
      , b.O_DATE 
        + ((cast((a.ORDERED_DATE - b.O_DATE) as INT) / 7 MOD 7) * 7)
           as SEVEN_DAY_WINDOW
      , sum(ORDER_QUANTITY) as ORDER_QUANTITY
from your_table a
join (
   select ITEM_NUMBER, min(ORDERED_DATE) as O_DATE
   from   your_table
   group by ITEM_NUMBER
   ) b
on a.ITEM_NUMBER=b.ITEM_NUMBER
group by 1,2
order by 1,2