Oracle sql:一次查询中按日期范围和总计的总计

问题描述 投票:0回答:1

我试图按日期范围显示总计,并在最后显示总计。

drop table EP;
create table EP (style varchar2(1), color varchar2(2), order_date date, order_qty number(2));

insert into EP values ('A','a1',to_date('01/01/2023','mm/dd/yyyy'), 10);
insert into EP values ('A','a2',to_date('01/01/2023','mm/dd/yyyy'), 12);
insert into EP values ('A','a3',to_date('01/01/2023','mm/dd/yyyy'), 15);
insert into EP values ('B','b1',to_date('01/05/2023','mm/dd/yyyy'), 5);
insert into EP values ('A','a3',to_date('01/05/2023','mm/dd/yyyy'), 8);
insert into EP values ('C','c1',to_date('01/06/2023','mm/dd/yyyy'), 3);
insert into EP values ('H','a1',to_date('01/07/2023','mm/dd/yyyy'), 25);
insert into EP values ('A','b3',to_date('01/07/2023','mm/dd/yyyy'), 10);
insert into EP values ('B','b3',to_date('01/10/2023','mm/dd/yyyy'), 15);

select * from EP;

我尝试过使用 ROLLUP,但由于我添加了更多列而无法使其工作。 on查询是否可以得到如下结果?

Expected Result:
------------------
STYLE COLOR DATE        QTY
A     a1    1/1/2023    10
A     a2    1/1/2023    12
A     a3    1/1/2023    15
Total:                  37
B     b1    1/5/2023    5
A     a3    1/5/2023    8 
Total:                  13
C     c1    1/6/2023    3 
Total:                  3
H     a1    1/7/2023    25
A     b3    1/7/2023    10
Total:                  35
B     b3    1/10/2023   15
Total:                  15
Grand Total:            103
sql oracle rollup
1个回答
0
投票

我可能更愿意将总计作为另一列而不是行,但以下是实现这两点的方法:

如果想要作为另一列,请使用

SUM() over()

select style, color, order_date, order_qty, 
  sum(order_qty) over (partition by order_date) as total_sum
from EP
风格 颜色 订单_日期 订单数量 总计_总和
A a1 23 年 1 月 1 日 10 37
A a2 23 年 1 月 1 日 12 37
A a3 23 年 1 月 1 日 15 37
B b1 23 年 1 月 5 日 5 13
A a3 23 年 1 月 5 日 8 13
C c1 23 年 1 月 6 日 3 3
H a1 23 年 1 月 7 日 25 35
A b3 23 年 1 月 7 日 10 35
B b3 23 年 1 月 10 日 15 15

如果想要另一行,请使用

UNION

select style, color, order_date, order_qty
from EP
union 
select '', '', order_date, sum(order_qty)
from EP
group by order_date
order by 3,1,2
风格 颜色 订单_日期 订单数量
A a1 23 年 1 月 1 日 10
A a2 23 年 1 月 1 日 12
A a3 23 年 1 月 1 日 15
23 年 1 月 1 日 37
A a3 23 年 1 月 5 日 8
B b1 23 年 1 月 5 日 5
23 年 1 月 5 日 13
C c1 23 年 1 月 6 日 3
23 年 1 月 6 日 3
A b3 23 年 1 月 7 日 10
H a1 23 年 1 月 7 日 25
23 年 1 月 7 日 35
B b3 23 年 1 月 10 日 15
23 年 1 月 10 日 15
© www.soinside.com 2019 - 2024. All rights reserved.