固定列 固定分隔符欄位列轉行

2021-10-14 16:54:27 字數 2545 閱讀 4707

在表t1中儲存如下內容,列2中的值用固定分隔符」,「進行分割:

請編寫sql,執行並得到如下結果:

不得使用儲存過程和自定義函式,mysql版本不限。

create table t1(c1 int,c2 varchar(5));

insert into t1 values(1,'a,b'),(2,'c,d,e'),(3,'f,g');

select a.c1,substring_index(substring_index(a.c2,',',b.help_topic_id+1),',',-1)

from

t1 a

join

mysql.help_topic b

on b.help_topic_id < (length(a.c2) - length(replace(a.c2,',',''))+1)

這張表的主要目的是要使用到它的自增id資料,也可以自建一張從0開始順序計數的表來使用,錶行數不能少於需轉換欄位的分隔符個數

獲得列會被分割成多少行

擷取到目標值後獲取最後乙個的值

實現sql2-5.7

select a.c1,a.c2,b.rn,a.len from

( select

c1,c2,

length(c2)-length(replace(c2,',','')) + 1 as len

from t1

) as a

inner join

( select @x:=@x+1 rn

from t1,(select @x:=0) a

) as b

on b.rn <= a.len

order by a.c1;

實現sql3-8.0

with cte_t as (

select

row_number() over w as rn,

c1,c2,

length(c2)-length(replace(c2,',','')) + 1 as len

from t1

window w as (order by c1)

)select

a.c1,

substring_index(substring_index(a.c2,',',b.rn),',',-1) as c2

from cte_t a,cte_t b

where b.rn <= a.len

order by a.c1;

實現sql4-最高效

with cte_t as (

select

json_arrayagg(

json_object(

"c1",c1,

"c2",cast(concat('["',replace(c2,",",'","'),'"]') as json))

) json_value

from t

)select j.* from

cte_t,json_table(

json_value,

'$[*]'

columns(

c1 int path '$.c1' ,

nested path '$.c2[*]' columns (c2 text path '$')

)) as j;

參考:

Hive的列分隔符和行分隔符

在建立hive表時,預設行分隔符 a 列分隔符 n 這兩項也是可以設定的。在實際開發中,一般預設使用預設的分隔符,當然有些場景下也會自定義分隔符。spark hive use test db 建立外部表 create external table test tb user id bigint com...

hive的列分隔符和行分隔符的使用

目錄 一 hive中預設的分割符如下 二 分隔符的指定與使用 三 建好表之後更改字段分隔符 分隔符描述 n 行分隔符 a欄位分隔符 001 barray struct的元素間的分隔符,map的鍵值對與鍵值對間分隔符 002 cmap中鍵與值之間的 分隔符 003 hive中在建立表時,一般會根據匯入...

多列轉一列,並加分隔符

create table table 1 id int,name varchar 8 go insert into table 1 select 1,tom union all select 2,john union all select 3,jerry go輸出結果 1,2,3 declare s...