如何把sqlserver中的列轉換成行,行轉換成列,顯示。
阿新 • • 發佈:2019-02-17
create database arron go use arron go -- createTable init Data create table students ( name varchar(25), class varchar(25), grade int ) insert into students values ('張三','語文',20) insert into students values ('張三','數學',90) insert into students values ('張三','英語',50) insert into students values ('李四','語文',81) insert into students values ('李四','數學',60) insert into students values ('李四','英語',90) -- solution1 select * from students pivot( max(grade) FOR [class] IN ([語文],[數學],[英語]) ) AS pvt -- solution2 相當於自連線 select A.Name,A.grade as 語文,B.grade as 數學,C.grade as 英語 from students A,students B,students C where A.Name=B.Name and B.Name=C.Name and A.class='語文' and B.class='數學' and C.class='英語' -- solution3 select name, max(case when s.class='語文' then s.grade end) as 語文, max(case when s.class='數學' then s.grade end) as 數學, max(case when s.class='英語' then s.grade end) as 英語 from students s group by name --在有id 的情況下 create table students2 ( id int primary key identity(1,1), name varchar(25), class varchar(25), grade int ) insert into students2 values ('張三','語文',20) insert into students2 values ('張三','數學',90) insert into students2 values ('張三','英語',50) insert into students2 values ('李四','語文',81) insert into students2 values ('李四','數學',60) insert into students2 values ('李四','英語',90) -- 原先的solution1(有問題) select * from students2 pivot( max(grade) FOR [class] IN ([語文],[數學],[英語]) ) AS pvt -- 原先的solution2 (ok) select A.Name,A.grade as 語文,B.grade as 數學,C.grade as 英語 from students A,students2 B,students2 C where A.Name=B.Name and B.Name=C.Name and A.class='語文' and B.class='數學' and C.class='英語' -- 原先的solution3 (ok) select name, max(case when s.class='語文' then s.grade end) as 語文, max(case when s.class='數學' then s.grade end) as 數學, max(case when s.class='英語' then s.grade end) as 英語 from students s group by name --unpivot 函式使用 create table test1(id int,name varchar(20), Q1 int, Q2 int, Q3 int, Q4 int) insert into test1 values(1,'a',1000,2000,4000,5000) insert into test1 values(2,'b',3000,3500,4200,5500) --實現的sql select * from test1 select id ,[name],[jidu],[xiaoshou] from test1 unpivot ( xiaoshou for jidu in ([q1],[q2],[q3],[q4]) ) as f --- 以下的sql 可以替換上面的sql select id,[name], jidu='Q1', xiaoshou=(select Q1 from test1 where id=a.id) from test1 as a union select id,[name], jidu='Q2', xiaoshou=(select Q2 from test1 where id=a.id) from test1 as a union select id,[name], jidu='Q3', xiaoshou=(select Q3 from test1 where id=a.id) from test1 as a union select id,[name], jidu='Q4', xiaoshou=(select Q4 from test1 where id=a.id) from test1 as a