【sql】SQL 行轉列的兩種做法
阿新 • • 發佈:2019-02-10
create table tb(姓名 varchar(10),課程 varchar(10),分數 int)
insert into tb values('張三','語文',74)
insert into tb values('張三','數學',83)
insert into tb values('張三','物理',93)
insert into tb values('李四','語文',74)
insert into tb values('李四','數學',84)
insert into tb values('李四','物理',94)
go!
select * from tb -- 使用case when (SQL2000以上) select 姓名, max(case 課程 when '語文' then 分數 else 0 end)語文, max(case 課程 when '數學'then 分數 else 0 end)數學, max(case 課程 when '物理'then 分數 else 0 end)物理 from tb group by 姓名 -- 使用pivot select * from tb pivot(max(分數) for 課程 in (語文,數學,物理))a
-- 另外也可以通過寫儲存過程實現,但比較麻煩。