最近在慕課上 看mysql教程 裡面關於行轉列的教程不錯 貼上練習sql 做個記錄
簡單行轉列
select
a.user_name,
sum(b.kills)
from
user1 a
join user_kills b on a.id = b.user_id
group
by user_name;
cross join 行列轉換
select * from (
select
sum(kills) as
'孫悟空'
from
user1 a
join user_kills b on a.id = b.user_id
and a.user_name = '孫悟空'
) across
join (
select
sum(kills) as
'沙甥'
from
user1 a
join user_kills b on a.id = b.user_id
and a.user_name = '沙甥'
) bcross
join (
select
sum(kills) as
'豬八戒'
from
user1 a
join user_kills b on a.id = b.user_id
and a.user_name = '豬八戒'
) c;
case行列轉換
select
sum(
case
when user_name = '孫悟空'
then
kills
end) as
'孫悟空',
sum(
case
when user_name = '沙甥'
then
kills
end) as
'沙甥',
sum(
case
when user_name = '豬八戒'
then
kills
end) as
'豬八戒'
from
user1 a
join user_kills b on a.id = b.user_id;
單列轉多行
select
user_name,
replace (
substring(
substring_index(mobile, ',', a.id),
char_length(
substring_index(mobile, ',', a.id - 1)
) + 1
),',',
'') as mobile
from
tb_sequence a
cross
join (
select
user_name,
concat(mobile, ',') as mobile,
length(mobile) - length(replace(mobile, ',', '')) + 1
size
from
user1 b
) b on a.id <= b.size;
mysql行列轉換 mysql行列轉換
1.一維轉二維 上圖為成績表中資料,現希望將資料轉換為下圖。靜態 轉化為二維表後的列名及列數是確定不變的,本例中即course只有數學 語文 英語這三門課。select s name,max if course 數學 score,0 as 數學,max if course 語文 score,0 as...
mysql行列轉換例子 mysql行列轉換示例
現把轉換方法列舉如下 1 縱表轉橫表 縱表結構 tablea name course grade 張三語文 張三數學 張三英語 李四語文 李四數學 橫表結構 tableb name 語文數學 英語張三 李四方法一 select name,sum case course when 語文 then gr...
mysql行列轉換
列轉行 利用max case when then max 聚合函式 取最大值 casecoursewhen 語文 thenscoreelse0end 判斷 as 語文 別名作為列名 select name max case when course 語文 then score end as語文,max...