MySQL 列轉行用法實現

2021-09-27 13:12:00 字數 1689 閱讀 7030

需求

需要將如下所示原始表資料轉為結構化的資料按行顯示:

轉為結構化資料:

解決方法

如果是單條記錄通過substring_index容易實現,sql語句如下:

select name,substring_index(accounts,',',1) account from personaccounts where id=1

union

select name,substring_index(substring_index(accounts,',',2),',',-1) account from personaccounts where id=1

union

select name,substring_index(substring_index(accounts,',',3),',',-1) account from personaccounts where id=1

查詢結果如下:

對於資料很多的話需要借助中間表來實現:

create table digits (digit int(1));

insert into digits

values

(0),

(1),

(2),

(3),

(4),

(5),

(6),

(7),

(8),

(9);

-- 建立序列表

create table sequence (seq int(3));

insert into sequence (

select

d1.digit + d2.digit * 10

from

digits d1

cross join digits d2

);

查詢列轉為行的語句如下:

select 

name,

substring_index(substring_index(accounts, ',', seq), ',' ,- 1 ) accounts,

seqfrom

sequence

cross join personaccounts

where

seq between 1 and (

select 1 + length(accounts) - length(replace(accounts, ',', ''))

)order by name, accounts;

結果如下:

參考:mysql group_concat的反向應用實現(mysql列轉行)

Mysql 列轉行 例項

箱表 create table yoshop shang activity box id int 11 not null auto increment comment 編號 activity id int 11 not null comment 活動id number int 11 not null...

Mysql 採用列轉行

欄位的拆分 使用函式substring index str,delim,count str 拆分物件 delim 拆分標識 substring index 搜尋時執行區分大小寫的匹配 delim count 拆分方式 如果 count為正,則返回最終分隔符左側的所有內容 從左側開始計算 如果coun...

mysql 列轉行,合併字段

列轉行 利用max case when then max 聚合函式 取最大值 casecoursewhen 語文 thenscoreelse0end 判斷 as 語文 別名作為列名 select name max case when course 語文 then score end as語文,max...