SQL行轉列
阿新 • • 發佈:2017-05-12
png 英語 姓名 create case when src clas 行轉列 序號
一、使用場景
當系統中有匯總和明細的需求時,一般通過SQL來實現,匯總 就是 根據條件顯示出全部的數據,明細 就是 一條匯總對應的詳細信息。
行轉列通常用於實現明細的時候。
二、舉例實現
1.當表中不存在id時:
1). 新建表student,姓名(name)、學科(subject)、成績(score)
create table student(name nvarchar(20),subject nvarchar(20),score int)
2). 插入數據
insert into student values(‘張三‘,‘語文‘,80),(‘張三‘,‘數學‘,90),(‘張三‘,‘英語‘,75) insert into student values(‘李四‘,‘語文‘,75),(‘李四‘,‘數學‘,93),(‘李四‘,‘英語‘,56) insert into student values(‘王五‘,‘語文‘,87),(‘王五‘,‘數學‘,67),(‘王五‘,‘英語‘,83)
3). 方式一實現:使用case when ... then ... end
select name, max(case subject when ‘語文‘ then score else 0 end) ‘語文‘, max(casesubject when ‘數學‘ then score else 0 end) ‘數學‘, max(case subject when ‘英語‘ then score else 0 end) ‘英語‘, SUM(score) as ‘總分‘, cast(AVG(cast(score as decimal(10,2))) as decimal(10,2)) as ‘平均分‘ from student group by name
4) 方式二實現:自己和自己關聯
select a.name,a.score,b.score,c.score,(a.score+b.score+c.score) ‘總分‘,CAST((a.score+b.score+c.score)/3.0 as decimal(5,2)) ‘平均分‘ from student a,student b,student c where a.name = b.name and b.name = c.name and a.subject=‘語文‘ and b.subject=‘數學‘ and c.subject=‘英語‘
5) 方式三實現:使用pivot
select * from student pivot(max(score) for subject in (語文,數學,英語))a
2.當表中存在id時,
1). 新建表tb_student,序號(id)、姓名(name)、學科(subject)、成績(score)
create table tab_student(id int,name nvarchar(20),subject nvarchar(20),score int)
2). 插入數據:
insert into tab_student values (1,‘張三‘,‘語文‘,76),(2,‘張三‘,‘數學‘,85),(3,‘張三‘,‘英語‘,67) insert into tab_student values (3,‘李四‘,‘語文‘,87),(4,‘李四‘,‘數學‘,32),(5,‘李四‘,‘英語‘,85) insert into tab_student values (6,‘王五‘,‘語文‘,83),(7,‘王五‘,‘數學‘,90),(8,‘王五‘,‘英語‘,80)
3) 方式一實現:使用 case when
select name,MAX(case subject when ‘語文‘ then score else 0 end) as ‘語文‘, MAX(case subject when ‘數學‘ then score else 0 end) as ‘數學‘, MAX(case subject when ‘英語‘ then score else 0 end) as ‘英語‘, SUM(score) ‘總數‘, cast(AVG(CAST(score as decimal(10,2))) as decimal(10,2)) ‘平均數‘ from tab_student group by name
4). 方式二實現:自己關聯自己
select a.name,a.score,b.score,c.score,(a.score+b.score+c.score) ‘總分‘,CAST((a.score+b.score+c.score)/3.0 as decimal(5,2)) ‘平均分‘ from tab_student a,tab_student b,tab_student c where a.name = b.name and b.name = c.name and a.subject=‘語文‘ and b.subject=‘數學‘ and c.subject=‘英語‘
5). 方式三實現不了:pivot
select * from tab_student pivot( max(score) for subject in (語文,數學,英語) )a
SQL行轉列