数据库实现根据逗号将一行数据分成多行数据,和后续一些操作.

1业务场景

现有NEWS_TYPE表,字段如下
在这里插入图片描述

2 按逗号拆分的sql语句

2.1达梦sql语句

select
distinct id,
regexp_substr(data, '[^,]+', 1, LEVEL) as data
from NEWS_TYPE
connect by LEVEL <= length(data) - length(regexp_replace(data. ',', '')) + 1
order by id

ps:LEVEL不可更改

2.2mysql语句

SELECT
	a.id,
	a.name,
	substring_index( substring_index( a.data, ',', b.help_topic_id + 1 ), ',',- 1 ) as data
FROM
	NEWS_TYPE a
	JOIN mysql.help_topic b ON b.help_topic_id < (
		length( a.data ) - length(
		REPLACE ( a.data, ',', '' ))+ 1)

3达到的效果

在这里插入图片描述

4对拆分结果进行分组统计的sql语句

4.1达梦sql语句

SELECT
	newTable.NAME,
	newTable.DATA,
	count(*) AS countNum 
FROM
	(
select
distinct id,
regexp_substr(data, '[^,]+', 1, LEVEL) as data
from NEWS_TYPE
connect by LEVEL <= length(data) - length(regexp_replace(data. ',', '')) + 1
order by id
) AS newTable 
WHERE
	1 = 1 
GROUP BY
	newTable.NAME,
	newTable.DATA

4.2mysql语句

SELECT
	newTable.NAME,
	newTable.DATA,
	count(*) AS countNum 
FROM
	(
	SELECT
		a.id,
		a.NAME,
		substring_index( substring_index( a.DATA, ',', b.help_topic_id + 1 ), ',',- 1 ) AS DATA 
	FROM
		NEWS_TYPE a
		JOIN mysql.help_topic b ON b.help_topic_id < ( length( a.DATA ) - length( REPLACE ( a.DATA, ',', '' ))+ 1 ) 
	) AS newTable 
WHERE
	1 = 1 
GROUP BY
	newTable.NAME,
	newTable.DATA

5达到的效果

在这里插入图片描述

6对分组结果进行行转列sql语句

6.1达梦sql语句

SELECT
	T.DATA,
	MAX( CASE T.NAME WHEN '名称1' THEN T.countNum ELSE 0 END ) AS '名称1',
	MAX( CASE T.NAME WHEN '名称2' THEN T.countNum ELSE 0 END ) AS '名称2',
	MAX( CASE T.NAME WHEN '名称3' THEN T.countNum ELSE 0 END ) AS '名称3' 
FROM
	(
SELECT
	newTable.NAME,
	newTable.DATA,
	count(*) AS countNum 
FROM
	(
select
distinct id,
regexp_substr(data, '[^,]+', 1, LEVEL) as data
from NEWS_TYPE
connect by LEVEL <= length(data) - length(regexp_replace(data. ',', '')) + 1
order by id
) AS newTable 
WHERE
	1 = 1 
GROUP BY
	newTable.NAME,
	newTable.DATA
		) AS T 
GROUP BY
	T.DATA

6.2mysql语句

SELECT
	T.DATA,
	MAX( CASE T.NAME WHEN '名称1' THEN T.countNum ELSE 0 END ) AS '名称1',
	MAX( CASE T.NAME WHEN '名称2' THEN T.countNum ELSE 0 END ) AS '名称2',
	MAX( CASE T.NAME WHEN '名称3' THEN T.countNum ELSE 0 END ) AS '名称3' 
FROM
	(
	SELECT
		newTable.NAME,
		newTable.DATA,
		count(*) AS countNum 
	FROM
		(
		SELECT
			a.id,
			a.NAME,
			substring_index( substring_index( a.DATA, ',', b.help_topic_id + 1 ), ',',- 1 ) AS DATA 
		FROM
			NEWS_TYPE a
			JOIN mysql.help_topic b ON b.help_topic_id < ( length( a.DATA ) - length( REPLACE ( a.DATA, ',', '' ))+ 1 ) 
		) AS newTable 
	WHERE
		1 = 1 
	GROUP BY
		newTable.NAME,
		newTable.DATA 
	) AS T 
GROUP BY
	T.DATA

7达到的效果

在这里插入图片描述
参考:https://www.cnblogs.com/muphy/p/10781505.html

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值