SQL:行列转换

方法很基础,但是容易理解和记忆

现在有两张表

纵表

 name  | subject | score
-------+---------+-------
 Kevin | Math    |    98
 Kevin | Physics |    97
 Kevin | Biology |   100
 Sam   | Math    |    95
 Sam   | Physics |    92
 Sam   | Biology |    89

横表

 name  | math | physics | biology
-------+------+---------+---------
 Kevin |   98 |      97 |     100
 Sam   |   95 |      92 |      89

行转列(纵表转横表) 

方法:在聚合函数中使用CASE表达式

select name,
sum(case when subject = 'Math' then score else null end) as Math,
sum(case when subject = 'Physics' then score else null end) as Physics,
sum(case when subject = 'Biology' then score else null end) as Biology
from rowtest
group by name;

列转行(横表转纵表)

方法:先分别查询各科成绩(以math为例,在新列subject中添加科目名称math,然后math的值放入新列score),然后用union合并起来

select name, 'Math' as subject, math as score from columntest
union
select name, 'Physics' as subject, physics as score from columntest
union
select name, 'Biology' as subject, biology as score from columntest
order by name;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值