赞
踩
行列转换只要弄清是什么样的数据可以进行行列转换就会变的很简单。
情况一:若给出文字,文字描述出现“…的…”
select
col1 as col1,
max(case col2 when "c" then col3 else 0 end) as c,
max(case col2 when "d" then col3 else 0 end) as d,
max(case col2 when "e" then col3 else 0 end) as e,
from tb
group by col1;
-- 或者用 if() 代替 case...end
select
col1 as col1,
max(if(col2="c"), col3, 0) as c,
max(if(col2="d"), col3, 0) as d,
max(if(col2="e"), col3, 0) as e
from tb
group by col1;
注意:
https://www.cnblogs.com/30go/p/8328869.html
select
DDate,
count(if(shengfu="胜", 1, null)) as "胜",
count(if(shengfu="负", 1, null)) as "负",
from tb
group by DDate;
...的...
字眼,故需先进行行列转换。学生id
、课程id
、课程分数
,由此不需要join就可以完成行列转换-- 1. 先进多行转多列,得到:...的...形式。这里得到学生的成绩
with tmp as (
select
student_id,
max(if(cname=1, sc.score, 0)) as bio,
max(if(cname=2, sc.score, 0)) as pe,
from score
group by student_id;
having pe < bio
)
select
sid,
sname
from tmp
left join student on student_id = sid
where bio < pe;
满足以下1个条件,则可以进行多行转单列:
select
col1 as col1,
col2 as col2,
concat_ws(",", collect_list(cast(col3 as string))) as col3
from tb
group by col1, col2;
多列转多行就是多行转多列的逆过程:
一个select转一列,然后将多个select用union all 拼接起来:
select col1, "c" as col2, col2 as col3 from tb;
union all
select col1, "d" as col2, col3 as col3 from tb;
union all
select col1, "c" as col2, col4 as col3 from tb;
单列转多行就是多行转单列的逆过程:
select
col1,
col2,
tb2.col3 as col3
from tb lateral view explode(split(col3, ",")) tb2 as col3
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。