数据表介绍
提示:这里只是提供一个练习的数据表,没有任何实际含义。
表名:dep_score
字段:
- a:年份
- b:部门
- c:绩效得分
表数据:
a | b | c |
---|---|---|
2014 | B | 9 |
2015 | A | 8 |
2014 | A | 10 |
2015 | B | 7 |
问题一:多行转多列
问题描述:
将上述表内容转为如下输出结果所示。
a | col_A | col_B |
---|---|---|
2014 | 10 | 9 |
2015 | 8 | 7 |
SQL脚本:
select a,
max(case when b='A' then c end) as col_A,
max(case when b='B' then c end) as col_B
from dep_score
group by a
;
问题二:多列转多行
问题描述:
也就是将问题一得到的结果如何转化回原始的表,这里将问题一得到的结果表记为dep_score_new
。
SQL脚本:
select a,b,c
from (
select a, 'A' as b, col_a as c
from dep_score_new
union all
select a, 'B' as b, col_b as c
from dep_score_new
)t
;
问题三:当同一部门存在多个绩效,如何对其进行行转列操作
问题描述:
其实其存在多个值的时候,更符合我们实际遇到的情景。
现在我们使用的数据表 dep_score
内容如下:
a | b | c |
---|---|---|
2014 | B | 9 |
2015 | A | 8 |
2014 | A | 10 |
2015 | B | 7 |
2014 | B | 6 |
SQL脚本:
select a,
max(case when b='A' then c end) as col_A,
max(case when b='B' then c end) as col_B
from (
select a,b,
concat_ws(",", collect_set(cast(c as string))) as c
from dep_score
group by a,b
)tmp
group by a
;
这样我们就能够得到下面的结果:
a | col_A | col_B |
---|---|---|
2014 | 10 | 6,9 |
2015 | 8 | 7 |
一天学习一点点~