MySQL中行轉列與列轉行

2021-10-06 08:00:38 字數 3635 閱讀 8388

mysql中行轉列與列轉行

行轉列,即為將mysql中原本同一列(字段)下的內容轉換為同一行的多個字段。

如上圖一張成績表,進行如下轉換:

1、行轉列轉換後,

轉換後,變為如下顯示:

明顯可以看出,此時將userid分為了一組,每組都有語文、數學、英語、政治這幾門課的成績。

方式一:用if語句轉換

select user_id,

sum(if(

`subject`

='語文'

,score,0)

)as'語文'

,sum(if

(`subject`

='數學'

,score,0)

)as'數學'

,sum(if

(`subject`

='英語'

,score,0)

)as'英語'

,sum(if

(`subject`

='政治'

,score,0)

)as'政治'

from t_score

group

by user_id

因為不對應的學科,若不加sum或max,用if求出的結果必然是0,所以需要在if外巢狀乙個sum或max,求出最大值或是總和,即為分組後所求的分數

如語文:分組後,乙個編號學生除了「語文」這一字段外,其他科目欄位都不是「語文」,因此數學、英語、政治都為0,若不加sum或者max,則資料會顯示為0,加了max或sum,就可以取到「語文」這一列的資料

方式二:用case…when…then語句轉換

select user_id,

sum(

case

`subject`

when

'語文'

then score else

0end)as

'語文'

,sum

(case

`subject`

when

'數學'

then score else

0end)as

'數學'

,sum

(case

`subject`

when

'英語'

then score else

0end)as

'英語'

,sum

(case

`subject`

when

'政治'

then score else

0end)as

'政治'

from t_score

group

by user_id

2、行轉列,合併字段顯示轉換後,變為如下顯示:

將科目與分數拼接在一起

select userid,group_concat(

`subject`

,":"

,score)

as 成績 from t_score

group

by user_id

3、行轉列,並求出各個科目的總成績和每個學生的總成績。轉換後,如下圖顯示:

需要將total列求出來,並求出乙個單行total行,與利用union與前面三行拼接到一起(union 不去重,union去重)

select user_id,

sum(if(

`subject`

='語文'

,score,0)

)as 語文,

sum(if(

`subject`

='數學'

,score,0)

)as 數學,

sum(if(

`subject`

='英語'

,score,0)

)as 英語,

sum(if(

`subject`

='政治'

,score,0)

)as 政治,

sum(score)

as total

from tb_score

group

by user_id

union

select

'total'

,sum(if

(`subject`

='語文'

,score,0)

)as 語文,

sum(if(

`subject`

='數學'

,score,0)

)as 數學,

sum(if(

`subject`

='英語'

,score,0)

)as 英語,

sum(if(

`subject`

='政治'

,score,0)

)as 政治,

即將上面的列,轉為下面的行

通過將每個userid對應的多個科目的成績查出來,通過union all將結果集加起來

select user_id,

'語文'

as course,cn_score as score from tb_score1

union

allselect user_id,

'數學'

as course,math_score as score from tb_score1

union

allselect user_id,

'英語'

as course,en_score as score from tb_score1

union

allselect user_id,

'政治'

as course,po_score as score from tb_score1

order

by user_id

union與union all的區別:

1、去重:union會去重,union all不會

2、排序:union會排序,union all不會

3、效率:union all不會去重和排序,效率比union高

SQL Server 中行轉列 列轉行

行轉列 create database test on primary name test.mdf filename d project test.mdf size 10mb,filegrowth 15 log on name test.ndf filename d project test.ldf...

SQL中行轉列 列轉行

sql行轉列 列轉行 這個主題還是比較常見的,行轉列主要適用於對資料作聚合統計,如統計某類目的商品在某個時間區間的銷售情況。整理測試資料 create table wyc test id int 32 not null auto increment name varchar 80 default n...

hive中行轉列 列轉行的實現

行轉列實現 表資訊 場景一 使用concat ws和collect set函式 說明 collect set函式可以返回乙個array型別。concat ws函式可以拼接陣列,如下 場景二 有時候如果需要對指標字段求和,則上述sql改寫成如下 場景三 使用str to map和explode函式以及...