我有一张如下表格,我需要得到詹姆斯和琼斯以及整体总数的小计。
有些人可以通过仅使用plsql
帮助我找到答案order no | name | amount
order 1 | james | 400
order 2 | jones | 6000
order 3 | james | 100
O / P
order 1 | james | 400
order 3 | james | 6000
total | null | 6400
order 2 | jones | 100
overall | null | 6500
答案 0 :(得分:2)
您可以使用rollup
:
select
case grouping(order_no)+ grouping(name)
when 2 then 'overall'
when 1 then 'total'
else order_no
end as order_no,
name,
sum(amount) as amount
from t
group by rollup(name, order_no)
产地:
order 1 james 400
order 3 james 100
total james 500
order 2 jones 6000
total jones 6000
overall 6500
请注意,我保留了名称的总数,以便能够确定哪个用户的总数。
答案 1 :(得分:0)
这有点傻,我完全同意Gurv的观点,但这里是使用plsql并借用GURV解决方案的解决方案。
create table mytable (
order_no varchar(30),
name varchar2(30),
amount number
)
Insert into MYTABLE (ORDER_NO,NAME,AMOUNT) values ('1','james',4000);
Insert into MYTABLE (ORDER_NO,NAME,AMOUNT) values ('2','jones',6000);
Insert into MYTABLE (ORDER_NO,NAME,AMOUNT) values ('3','james',6000);
DECLARE
CURSOR totalByPerson IS
select
case grouping(order_no)+ grouping(name)
when 2 then 'overall'
when 1 then 'total'
else order_no
end as order_no,
name,
sum(amount) as amount
from mytable
group by rollup(name, order_no);
BEGIN
FOR person_rec in totalByPerson
LOOP
DBMS_OUTPUT.PUT_LINE(person_rec.order_no || '-'|| person_rec.name||' - '|| person_rec.amount );
END LOOP;
END;