SQL 行轉列,列轉行

2021-10-23 16:40:43 字數 2176 閱讀 9343

行列轉換在做報表分析是還是經常會遇到的

行列轉換就是如下圖所示兩種展示形式互相轉換

只是做測試,建表比較隨意

create

table student(

name varchar(20

),subject int(10

),score int(10

))

insert

into student(name,subject,score)

values

("小華",1

,12);

insert

into student(name,subject,score)

values

("小華",2

,13);

insert

into student(name,subject,score)

values

("小華",3

,14);

insert

into student(name,subject,score)

values

("大華",1

,35);

insert

into student(name,subject,score)

values

("大華",2

,11);

insert

into student(name,subject,score)

values

("大華",3

)as 語文,

max(

case

when subject =

2then score

else

0end

)as 數學,

max(

case

when subject =

3then score

else

0end

)as 英語

'語文'

as subject,

max(

'語文'

)as score

from student group

by name

union

select

name,

'數學'

as subject,

max(

'數學'

)as score

from student group

by name

union

select

name,

'英語'

as subject,

max(

'英語'

python 列轉行 SQL 行轉列,列轉行

sql 行轉列,列轉行 行列轉換在做報表分析時還是經常會遇到的,今天就說一下如何實現行列轉換吧。行列轉換就是如下圖所示兩種展示形式的互相轉換 行轉列假如我們有下表 select from student pivot sum score for subject in 語文,數學,英語 通過上面 sql...

sql 行轉列,列轉行整合

原始資料及結構如下 when 語文 then t.score else 0 end 語文,sum case t.subject when 數學 then t.score else 0 end 數學 sum case t.subject when 英語 then t.score else 0 end ...

SQL 行轉列 列轉行11 15

原表tmp 問題,將課程放到列上去 用case when 或 if 外面再巢狀乙個sum即可。對於c name,轉成列 兩種方法結果一樣 case when 表示式1 then 值1 when 表示式2 then 值2 else 值 end select stu id,sum case when c...