SQLSERVER 行转列

WITH    data
          AS ( SELECT   '语文' subject_name ,
                        90 score ,
                        '张三' student_name ,
                        '一班' class_name
               UNION ALL
               SELECT   '数学' subject_name ,
                        92 score ,
                        '张三' student_name ,
                        '一班' class_name
               UNION ALL
               SELECT   '英语' subject_name ,
                        93 score ,
                        '张三' student_name ,
                        '一班' class_name
               UNION ALL
               SELECT   '语文' subject_name ,
                        89 score ,
                        '张三1' student_name ,
                        '一班' class_name
               UNION ALL
               SELECT   '数学' subject_name ,
                        82 score ,
                        '张三1' student_name ,
                        '一班' class_name
               UNION ALL
               SELECT   '英语' subject_name ,
                        81 score ,
                        '张三1' student_name ,
                        '一班' class_name
               UNION ALL
               SELECT   '英语' subject_name ,
                        91 score ,
                        '张三1' student_name ,
                        '一班' class_name
             )
    SELECT  *
    FROM    data PIVOT( MAX(score) FOR subject_name IN ( [语文], [数学], [英语] ) ) t;

1,关键函数PIVOT

2,subject_name IN ( [语文], [数学], [英语] )  把行subject_name值在 语文 数学 英语 里的数据转换成列

3,MAX(score)  取最大分数值作为列的值,除开subject_name和score列的其他列分组组合成行数据

查询结果:

 

posted @ 2021-08-17 17:57  杨jian  阅读(426)  评论(0编辑  收藏  举报