SQL(2) 行转列,列转行
1、行转列(sql sever)
-- 建表 CREATE TABLE StudentScores ( UserName NVARCHAR(20), -- 学生姓名 Subject NVARCHAR(30), -- 科目 Score FLOAT -- 成绩 ) -- 添加数据 INSERT INTO StudentScores SELECT 张三, 语文, 80 ; INSERT INTO StudentScores SELECT 张三, 数学, 90 ; INSERT INTO StudentScores SELECT 张三, 英语, 70 ; INSERT INTO StudentScores SELECT 张三, 生物, 85 ; INSERT INTO StudentScores SELECT 李四, 语文, 80 ; INSERT INTO StudentScores SELECT 李四, 数学, 92 ; INSERT INTO StudentScores SELECT 李四, 英语, 76 ; INSERT INTO StudentScores SELECT 李四, 生物, 88 ; INSERT INTO StudentScores SELECT 码农, 语文, 60 ; INSERT INTO StudentScores SELECT 码农, 数学, 82 ; INSERT INTO StudentScores SELECT 码农, 英语, 96 ; INSERT INTO StudentScores SELECT 码农, 生物, 78 ;
-- 对列转置 -- 使用PIVOT行转列 SELECT * FROM StudentScores PIVOT ( SUM(Score) FOR Subject IN ([语文],[数学],[英语],[生物]) ) T # 注意[语文],而不是‘语文’ select username, max(case when Subject=语文 then score else 0 end) 语文, max(case when Subject=数学 then score else 0 end) 数学, max(case when Subject=英语 then score else 0 end) 英语, max(case when Subject=生物 then score else 0 end) 生物 from StudentScores group by UserName;
2、列转行
USE yp; IF OBJECT_ID(NStudentScores2, NU) IS NOT NULL drop table StudentScores2; CREATE TABLE StudentScores2 (UserName varchar(10), "语文" float, "数学" float, "英语" float, "生物" float ) select * from StudentScores2; insert into StudentScores2 select username, max(case when Subject=语文 then score else 0 end) 语文, max(case when Subject=数学 then score else 0 end) 数学, max(case when Subject=英语 then score else 0 end) 英语, max(case when Subject=生物 then score else 0 end) 生物 from StudentScores group by UserName; # 注意单引号和双引号 select Username,语文 Subject,语文 score from StudentScores2 union all select Username,数学 Subject,数学 score from StudentScores2 union all select Username,英语 Subject,英语 score from StudentScores2 union all select Username,生物 Subject,生物 score from StudentScores2 order by UserName;
Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序;
Union All:对两个结果集进行并集操作,包括重复行,不进行排序;
