根据日期生成日期范围

时间:2014-08-12 09:43:27

标签: sql oracle plsql

假设我有这张表

   Date     Inventory Sold
----------  --------------
14/04/2014         9
15/04/2014        21 
16/04/2014        10
17/04/2014        20
18/04/2014        12
19/04/2014        25
20/04/2014        33

- 以及更多日期

如何将它制作成像这样的表

  Date Range     Inventory Sold
--------------  ----------------
   xxx-xxx             50
   xxx-xxx             44

Date Range假设是按周的范围,例如:14/04/2014 - 20/04/2014

2 个答案:

答案 0 :(得分:1)

按截短日期将数据分组为“整周”,例如:

with data as (
   select date '2014-04-14' sold_date, 9 inventory_sold from dual
   union all
   select date '2014-04-15', 21 from dual
   union all
   select date '2014-04-16', 10 from dual
   union all
   select date '2014-04-17', 20 from dual
   union all
   select date '2014-04-18', 12 from dual
   union all
   select date '2014-04-19', 25 from dual
   union all
   select date '2014-04-20', 33 from dual
   union all
   select date '2014-04-21',  1 from dual
)
select trunc(sold_date,'IW') week_start
     , sum(inventory_sold)
  from data
 group by trunc(sold_date,'IW')
 order by trunc(sold_date,'IW')

IW是ISO周,意味着它使用星期一 - 星期日。 Trunc(日期,'IW')给出了星期一的星期一。

如果您需要显示范围,则可以使用以下内容:

with data as (
   select date '2014-04-14' sold_date, 9 inventory_sold from dual
   union all
   select date '2014-04-15', 21 from dual
   union all
   select date '2014-04-16', 10 from dual
   union all
   select date '2014-04-17', 20 from dual
   union all
   select date '2014-04-18', 12 from dual
   union all
   select date '2014-04-19', 25 from dual
   union all
   select date '2014-04-20', 33 from dual
   union all
   select date '2014-04-21',  1 from dual
)
select to_char(trunc(sold_date,'W'),'DD-MM-YY')
       ||'->'||
       to_char(trunc(sold_date,'W')+6,'DD-MM-YY') week
     , sum(inventory_sold)
  from data
 group by trunc(sold_date,'W')
 order by trunc(sold_date,'W')

希望这很有用: - )

答案 1 :(得分:0)

指着你:

 WHERE
                date >= 'selected_date_low'
                AND date <= '$selected_date_high'