SQL SERVER行列转换

行列转换
要用到SQL SERVER
CASE [字段名] WHEN ‘字段名’ THEN [字段的数据值] ELSE 0 END
CASE WHEN [字段名] = ‘字段名’ THEN [字段的数据值] ELSE 0 END
判断一个字段名是否和这个改字段名相等,如果相等,就得到字段的数据值,否则为0.

Student

uid (key)nameage
1张三22
2李四22
3王五19

score

sid (key)snamescoreuid
1数学1111
2英语1221
3语文1191
4数学1212
5英语1222
6语文1232
7数学1313
8英语1423
9语文1393

输出表格式

uidagename数学英语语文
SELECT  s3.uid,s3.age,s3.name,
SUM(CASE s3.sname WHEN '英语' THEN scores ELSE 0 END) AS '数学',
SUM(CASE s3.sname WHEN '数学' THEN scores ELSE 0 END)     AS '英语',
SUM(CASE s3.sname WHEN '语文' THEN scores ELSE 0 END) AS '语文'   
FROM (select s1.uid,s1.name,s1.age,sname,scores,sid from 
dbo.student as s1,dbo.score as s2 where s1.uid = s2.uid) as s3
GROUP BY  s3.uid,s3.age,s3.name;
    原文作者:JavaIsMyLife
    原文地址: https://www.jianshu.com/p/50a71d98a28b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞