当前位置:   article > 正文

SQL题型:根据逗号拆分列_sql将一列按逗号拆分多列

sql将一列按逗号拆分多列

例1:
表:
在这里插入图片描述
要实现的结果:
在这里插入图片描述
代码:

select a.id as hyId,substring_index(substring_index(a.ch_ry_mc, ',',b.help_topic_id + 1 ),',', - 1) AS CH_RY_ID
FROM rsgl_hygl_hyxx a
JOIN mysql.help_topic b ON b.help_topic_id < (
length(a.ch_ry_mc) - length(REPLACE(a.ch_ry_mc, ',', '')) + 1)
where a.id = '1481518766988763138'
  • 1
  • 2
  • 3
  • 4
  • 5

例2:对于特定的某天,哪个id的value值最多。需要对value字段拆解
在这里插入图片描述

# 设定前一天的日期为2023-05-01
with a AS
(select a.id,substring_index(substring_index(a.value, ',',b.help_topic_id + 1),',', - 1) AS value_c
FROM table_a a
JOIN mysql.help_topic b ON b.help_topic_id < (length(a.value) - length(REPLACE(a.value, ',', '')) + 1) 
where a.dt = '2023-05-01'),
b as
(select id,count(value_c) as cv
from a
group by id)

select id,cv
from b
where cv = (select max(cv) from b )
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/268442
推荐阅读
相关标签
  

闽ICP备14008679号