1. 程式人生 > >sql 行轉列 語句

sql 行轉列 語句

【一】行轉列

1,查詢原始的資料

/***這次練習的主題,行轉列,列轉行***/
select * from Scores

2,得到姓名,通過group by

select Student as '姓名'
from Scores
group by Student
order by Student

3,再加上max, case……when

複製程式碼
select Student as '姓名',
max(case Subject when '語文' then Score else 0 end) as '語文' ,--如果這個行是“語文”,就選此行作為列max(case Subject when
'英語' then Score else 0 end ) as '英語'
from Scores
group by Student
order by Student
複製程式碼

檢視其它資料時,看到另外一種方法,用pivot

複製程式碼
--group by, avg/max, pivot。這裡用max和avg,結果都一樣,有什麼區別嗎?有點不明白
--參考網上的資料,用法如下
/*
pivot(
  聚合函式(要轉成列值的列名)
  for 要轉換的列
  in(目標列名)
  )
*/
select Student as '姓名',
avg(語文) as '語文',
avg(英語) as '英語'
from Scores
pivot(
avg
(Score) for Subject
in (語文,英語)
)as NewScores
group by Student
order by Student asc