热线电话:13121318867

登录
2020-09-06 阅读量: 831
SQL中的case when与纵横表转换

SQL中的CASE WHEN用法

其语法如下:

1)case vlaue when [compare-value]then reslut [when[compare-value]] then result ...] [else result] end

(2)case when [condition] then result [when[condition]then result...][else result] end

第一形式当value=compare-value时返回result

第二形式当第一个为真值的condition出现时,返回该条件的结果,如果没有匹配的结果值,那么else后的结

果将被返回,如果没有else部分,那么返回null


问题:假设有张学生成绩表(tb)如下:
姓名 课程 分数
张三 语文 74
张三 数学 83
张三 物理 93
李四 语文 74
李四 数学 84
李四 物理 94
想变成(得到如下结果):
姓名 语文 数学 物理
---- ---- ---- ----
李四 74 84 94
张三 74 83 93
-------------------


select 姓名 as 姓名 ,
max(case 课程 when '语文' then 分数 else 0 end) 语文,
max(case 课程 when '数学' then 分数 else 0 end) 数学,
max(case 课程 when '物理' then 分数 else 0 end) 物理
from tb
group by 姓名;


75.0913
0
关注作者
收藏
评论(0)

发表评论

暂无数据