我有一些样本数据
age year score
0 2018 10
7 2019 20
11 2018 30
13 2019 40
14 2018 50
我想像
count
year
age 2018 2019
0-4 1 0
5-9 0 1
10-14 2 1
15-19 0 0
我想总结一下
total score
year
age 2018 2019
0-4 10 0
5-9 0 20
10-14 80 40
15-19 0 0
我tried.but它不能很好地工作,后来我尝试通过电子表格旋转。
如何使用SQL进行上述转换?
发布于 2019-09-21 06:30:36
一种方法是利用整数数学将年龄转化为他们的“年龄组”。7/5是1)。然后使用case语句创建2018和2019列。
select
age/5*5 as age_group_lower,
case year
when 2018 then
score
end as "2018",
case year
when 2019 then
score
end as "2019"
from scores;
age_group_lower 2018 2019
0 10
5 20
10 30
10 40
10 50
这可以在CTE中使用,并根据您的喜好进行汇总。
with score_years as (
select
age/5*5 as age_group_lower,
case year
when 2018 then
score
end as "2018",
case year
when 2019 then
score
end as "2019"
from scores
)
select
age_group_lower || '-' || age_group_lower + 4 as age_group,
sum("2018") as "2018", sum("2019") as "2019"
from score_years
group by age_group_lower
order by age_group_lower;
age_group 2018 2019
0-4 10
5-9 20
10-14 80 40
这是Postgres语法(抱歉,我不知道Oracle),但是这里没有什么是Oracle不能处理的。
https://stackoverflow.com/questions/58037424
复制相似问题