sql 语句系列(字符串之裂开)[八百章之第十三章]

创建分割列表

一张表:

先查询出来的效果是这样的:

mysql:

select emp_copy.deptno,GROUP_CONCAT(emp_copy.emps SEPARATOR ',') from emp_copy GROUP BY emp_copy.deptno

sql service:

with x(deptno,cnt,list,empno,len)
as(
select DEPTNO,COUNT(*) over (partition by deptno) cnt,CAST(ename as varchar(100)) ename,EMPNO,1 length
from emp
union all
select x.deptno,x.cnt,CAST(x.list +','+e.ENAME as varchar(100)) ename,e.EMPNO,x.len+1 length
from emp e,x
where e.DEPTNO=x.deptno and e.EMPNO>x.empno
)
select x.deptno,x.list
from x
where x.len=x.cnt

分割数据转换为多值int列表

'7654,7698,7782,7788' 切割为列表
mysql:

SELECT SUBSTRING_INDEX(substring_index('7654,7698,7782,7788',',',iter.id),',',-1) empno
from (SELECT id from T10) iter,(select '7654,7698,7782,7788' as vals) list
where iter.id<=(LENGTH('7654,7698,7782,7788')-LENGTH(REPLACE('7654,7698,7782,7788',',','')))+1

sql service

select SUBSTRING(c,2,CHARINDEX(',',c,2)-2) as empno from
(
select SUBSTRING(csv.emps,iter.pos,LEN(csv.emps)) c
from (select ','+'7654,7698,7782,7788'+','as emps from t1) csv,(select id as pos from t100) iter
where iter.pos<LEN(csv.emps)) x
where LEN(c)>1 and SUBSTRING(c,1,1)=','

原理和mysql一致。

提取n 个分割字符串

例如:'7654,7698,7782,7788'
你想提取的是第二个分割字符串7698

mysql:

select substring_index(substring_index(emp_copy.`name`,',',2),',',-1) name,emp_copy.`name`
from emp_copy
WHERE LENGTH(emp_copy.`name`)-LENGTH(REPLACE(emp_copy.`name`,',',''))>=1

sql service:
在sql service 中我就不去创建表了。
我在上一个例子的改动,也就是上面的分割数据转换为多值int列表

select ROW_NUMBER() over(partition by name order by len(c) desc) rn,c
from
(
select SUBSTRING(csv.emps,iter.pos,LEN(csv.emps)) c,'7654,7698,7782,7788' name
from (select ','+'7654,7698,7782,7788'+','as emps from t1) csv,(select id as pos from t100) iter
where iter.pos<LEN(csv.emps)
) x
where LEN(c)>1 and SUBSTRING(c,1,1)=','


把得到的结果拍个序号。
第一个就是完整的,然后取第一个第一个。
第二个是去除第一个字符的,那么取第一个就是第二个了。

原文地址:https://www.cnblogs.com/aoximin/p/12586263.html