水善利万物而不争,处众人之所恶,故几于道💦
文章目录
MySQL
1.行转列
把多行转成列。直接group,sum(if())
2.列转行
Hive
1.行转列
![](https://i-blog.csdnimg.cn/direct/4b880127cd974bcb923d49278f6c94f7.png)
sql
select
name,
sum(if(km='shuxue',cj,0)) shuxue,
sum(if(km='yuwen',cj,0)) yuwen,
sum(if(km='huaxue',cj,0)) huaxue
from hzl
group by name
![](https://i-blog.csdnimg.cn/direct/09ebe56d9d6f4d1ca764222cfd880ebc.png)
2.列转行
(1)侧窗
hive中除了可以用常规的union all 外,还可以用侧窗
sql
-- 侧窗写法
select
name,
km,
cj
from lzh2
lateral view
explode(map('yuwen',yuwen,'shuxue',shuxue,'huaxue',huaxue)) tmp as km,cj;
![](https://i-blog.csdnimg.cn/direct/702370fc202e4d2ca63a04aa1ac0077c.png)
(2)union
sql
-- 常规写法
select name,'shuxue' km,shuxue cj from lzh2
union all
select name,'yuwen',yuwen from lzh2
union all
select name,'huaxue',huaxue from lzh2;
![](https://i-blog.csdnimg.cn/direct/76ede3d0ec644496965b3b22b90beb85.png)