这是我的表员工:
员工表有三列,如下所示:
ID yearquarter Amount
7 20171 500
7 20172 300
7 20133 100
7 20174 200
7 20181 900
7 20182 500
7 20183 100
需要在年份中添加所有四个季度的金额,并且输出应该有单行 总计如下所示。 如果任何一年只有三个季度仍然需要添加所有三个 四分之一并将它们放在单行作为输出
输出:
ID yearquarter Amount
7 20171 1000
7 20181 1500
我正在尝试使用rank()函数但仍然遇到问题:
SELECT case when rank<=rank+3 then sum(amount) end as charges, max(yearquarter),id
FROM (
SELECT RANK() OVER (partition by id order by yearquarter) Rank, amount,yearquarter,id
FROM sample where id=10004)a
GROUP BY id
order by id
答案 0 :(得分:3)
只需按id
和年份
select id, left(yearquarter, 4) as yyyy, sum(amount)
from sample
group by id, left(yearquarter, 4)
order by yyyy;