我在计算总额时遇到问题。例如
id name date amount
1 A 2017 100
1 A 2018 200
2 B 2017 50
2 B 2016 100
A's total 300
B's total 150
Total 450
从表1中选择ID,名称,日期,金额表格,其中日期> 2015通过ID,金额订购;
我想计算A,B和AB的总金额。还添加新的列名。我应该使用哪个功能?谢谢
答案 0 :(得分:1)
一种方法使用grouping sets
:
select id, name, date, sum(amount) as amount
from table1
where date > 2015
group by grouping sets ( (id, name, date), (name), () );
我不确定要添加哪些新列名称。
编辑:
假设三个键列都不是NULL
,则可以将名称分配为:
select id,
(case when name is null then 'Total'
when id is null then 'name' || '''s Total'
else name
end) as name
date, sum(amount) as amount
from table1
where date > 2015
group by grouping sets ( (id, name, date), (name), () );
答案 1 :(得分:1)
SELECT id , SUM(amount)
FROM yourTable
GROUP BY id;