一个字段里有很多组数据,用冒号逗号隔开,如何把它们拆分成列,也区分出字段名和内容

这个A字段中的内容格式大概为“1字段名“:“1字段内容”,“2字段名“:“2字段内容”,“3字段名“:“3字段内容。。。。总之这个A字段中就是由很多组这些组成,需要把字段名和字段内容都拆分出来,字段名显示在列的第一行,字段内容自然就是对应的第二行。。。应该如何写语句?貌似还会用到行列转换

FineReport mmc0112 发布于 2022-12-9 10:46
1min目标场景问卷 立即参与
回答问题
悬赏:3 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共1回答
最佳回答
0
LoverLv4见习互助
发布于2022-12-9 10:47

drop table if exists temp_20221202;

create table temp_20221202(char_name varchar(1024));

insert into temp_20221202

values ('SWID:123456,XH:S-1234,SCCMJ:测试')

select max(t3.SWID) as SWID

   ,max(t3.XH) as XH 

,max(t3.SCCMJ) as SCCMJ

from (

select COALESCE((case when pre_char='SWID' THEN after_char end),'0') as SWID

,COALESCE((case when pre_char='XH' THEN after_char end),'0') as XH

,COALESCE((case when pre_char='SCCMJ' THEN after_char end),'0') as SCCMJ

from (

select SUBSTRING_INDEX(t.char_name_split,':',1) as pre_char

,SUBSTRING_INDEX(t.char_name_split,':',-1) after_char

from (SELECT a.char_name

    , substring_index(substring_index(a.char_name, ',', b.help_topic_id + 1), ',', - 1) AS char_name_split

FROM temp_20221202 a

INNER JOIN mysql.help_topic b

    ON b.help_topic_id < (length(a.char_name) - length(REPLACE(a.char_name, ',', '')) + 1)) t

) tt 

) t3

image.png

  • 2关注人数
  • 307浏览人数
  • 最后回答于:2022-12-9 10:47
    请选择关闭问题的原因
    确定 取消
    返回顶部