要一直走下去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

student_score表:
+------+---------+-------+
| name | subject | score |
+------+---------+-------+
| 张三 | 语文 | 78 |
| 张三 | 数学 | 88 |
| 张三 | 英语 | 98 |
| 李四 | 语文 | 89 |
| 李四 | 数学 | 76 |
| 李四 | 英语 | 90 |
| 王五 | 语文 | 89 |
| 王五 | 数学 | 66 |
| 王五 | 英语 | 91 |
+------+---------+-------+

变换为

+------+------+------+------+
| name | 语文 | 数学 | 英语 |
+------+------+------+------+
| 张三 | 78 | 88 | 98 |
| 李四 | 89 | 76 | 90 |
| 王五 | 89 | 66 | 91 |
+------+------+------+------+

方法一:

--使用decode函数
select 
ss.name,
max(decode(ss.subject,'语文',ss.score)) 语文,
max(decode(ss.subject,'数学',ss.score)) 数学,
max(decode(ss.subject,'英语',ss.score)) 英语 
from student_score ss 
group by ss.name

方法二:

--case when
select 
ss.name,
max(case ss.subject when '语文' then ss.score end) 语文,
max(case ss.subject when '数学' then ss.score end) 数学,
max(case ss.subject when '英语' then ss.score end) 英语 
from student_score ss 
group by ss.name;

方法三:

--left join
select 
t1.name,t1.score,t2.score,t3.score 
from 
(select name,score from student_score where subject='语文') t1 
left join 
(select name,score from student_score where subject='数学') t2 
on t1.name=t2.name 
left join 
(select name,score from student_score where subject='英语') t3 
on t2.name=t3.name;

方法四:

--union all
select u.name,max(u.yuwen) 语文,max(u.shuxue) 数学,max(u.yingyu) 英语 
from 
(
select name,score yuwen,0 shuxue,0 yingyu from student_score where subject='语文' 
union all 
select name,0,score,0 from student_score where subject='数学' 
union all 
select name,0,0,score from student_score where subject='英语'
) u 
group by 
u.name;

 

posted on 2020-08-09 23:22  要一直走下去  阅读(89)  评论(0编辑  收藏  举报