我在Oracle中有一个像这样的表:
+------------+-------------+------+-----------+
| date | day_of_week | item | num_order |
+------------+-------------+------+-----------+
| 2015-03-16 | Mon | a | 10 |
| 2015-03-16 | Mon | a | 10 |
| 2015-03-16 | Mon | c | 10 |
| 2015-03-15 | Sun | b | 10 |
| 2015-03-14 | Sat | a | 10 |
| 2015-03-13 | Fri | c | 10 |
| 2015-03-12 | Thu | a | 10 |
| 2015-03-11 | Wed | b | 10 |
| 2015-03-10 | Tue | c | 10 |
+------------+-------------+------+-----------+
我需要的是
num_order
所以基本上,我想看看
每隔7天,从星期三开始,每件商品的订单数量是多少
所以最后,我想看到这样的表:
+------------+------+-----------------+
| 7_start | item | total_num_order |
+------------+------+-----------------+
| 2015-03-11 | a | 40 |
| 2015-03-11 | b | 20 |
| 2015-03-11 | b | 20 |
| 2015-03-04 | c | 10 |
+------------+------+-----------------+
我该怎么做?如何将日期分为7天并始终从星期三开始?
答案 0 :(得分:0)
您可以按周编号分组。由于您希望在星期三开始,因此更容易将其基于ISO年份和week number(始终在星期一开始,没有NLS影响),并调整两天。您可以通过以下方式查看每个日期的调整后的周数:
select date_col, to_char(date_col - 2, 'IYYYIW') from <your_table>
您希望显示星期三的日期,以便您可以按照显示的另一种方式调整两天,并按(调整的)年份,周数和项目进行分组:
select trunc(date_col - 2, 'IW') + 2, item, sum(num_order)
from <your table>
group by trunc(date_col - 2, 'IYYY'), trunc(date_col - 2, 'IW'), item
将您的示例数据作为CTE:
with t (date_col, item, num_order) as (
select date '2015-03-16', 'a', 10 from dual
union all select date '2015-03-16', 'a', 10 from dual
union all select date '2015-03-16', 'c', 10 from dual
union all select date '2015-03-15', 'b', 10 from dual
union all select date '2015-03-14', 'a', 10 from dual
union all select date '2015-03-13', 'c', 10 from dual
union all select date '2015-03-12', 'a', 10 from dual
union all select date '2015-03-11', 'b', 10 from dual
union all select date '2015-03-10', 'c', 10 from dual
)
select trunc(date_col - 2, 'IW') + 2 as period_start,
item,
sum(num_order) as total_num_order
from t
group by trunc(date_col - 2, 'IYYY'), trunc(date_col - 2, 'IW'), item
order by trunc(date_col - 2, 'IYYY'), trunc(date_col - 2, 'IW'), item;
PERIOD_START ITEM TOTAL_NUM_ORDER
------------ ---- ---------------
04-MAR-15 c 10
11-MAR-15 a 40
11-MAR-15 b 20
11-MAR-15 c 20
您可以使用此替代效果:
group by to_char(date_col - 2, 'IYYYIW'), trunc(date_col - 2, 'IW'), item
...但无论哪种方式,如果您的数据将超过一年,您需要按年和周元素进行分组。