SELECT l_count, REGEXP_SUBSTR('add, daddf, dsdf, asdfa, dsfasd, dsfad','[^,]+',1,l_count) AS NAME
FROM dual
,(SELECT LEVEL l_count FROM DUAL CONNECT BY LEVEL<=100)
WHERE l_count <=LENGTH('add, daddf, dsdf, asdfa, dsfasd, dsfad') - LENGTH(REPLACE('add, daddf, dsdf, asdfa, dsfasd, dsfad',','))+1
select replace(regexp_substr(:idstring,'[^,]+',1,level),',',' ')
from dualconnect by level<=length(:idstring)-length(replace(:idstring,',',''))+1
一条SQL的法则是某位大师提出的,大家曾经在某个时期都乐此不彼的寻求各种的问题一条SQL法,但是大师的意思似乎被曲解,很多性能差,可读性差,灵活差的SQL都是这个原则产物,所谓画虎不成反成犬类。不过,解决问题始终是第一原则,这里还是给出一个比较有代表性的一条SQL方法。
SELECT country,max(substr(city,2)) city
FROM
(SELECT country,sys_connect_by_path(city,',') city
FROM
(SELECT country,city,country||rn rchild,country||(rn-1) rfather
FROM
(SELECT test.country ,test.city,row_number() over (PARTITION BY test.country ORDER BY
test.city) rn
FROM test))
CONNECT BY PRIOR rchild=rfather START WITH rfather LIKE '%0')
GROUP BY country;
下面分步解析,有4个FROM,就有4次结果集的操作。
step 1 给记录加上序号rn
SQL> SELECT test.country ,test.city,row_number() over (PARTITION BY test.country ORDER
BY test.city) rn
2 FROM test
3 /
COUNTRY CITY RN
-------------------- -------------------- ----------
日本 大阪 1
日本 东京 2
中国 上海 1
中国 台北 2
中国 香港 3
step 2 创造子节点父节点
SQL> SELECT country,city,country||rn rchild,country||(rn-1) rfather
2 FROM
3 (SELECT test.country ,test.city,row_number() over (PARTITION BY test.country ORDER
BY test.city) rn
4 FROM test)
5 /
日本 大阪 日本1 日本0
日本 东京 日本2 日本1
中国 上海 中国1 中国0
中国 台北 中国2 中国1
中国 香港 中国3 中国2
step 3 利用sys_connect_by_path生成结果集
SELECT country,sys_connect_by_path(city,',') city
FROM
(SELECT country,city,country||rn rchild,country||(rn-1) rfather
FROM
(SELECT test.country ,test.city,row_number() over (PARTITION BY test.country ORDER BY
test.city) rn
FROM test))
CONNECT BY PRIOR rchild=rfather START WITH rfather LIKE '%0'
日本 ,大阪
日本 ,大阪,东京
中国 ,上海
中国 ,上海,台北
中国 ,上海,台北,香港
step 4 最终步骤,筛选结果集合
SQL> SELECT country,max(substr(city,2)) city
2 FROM
3 (SELECT country,sys_connect_by_path(city,',') city
4 FROM
5 (SELECT country,city,country||rn rchild,country||(rn-1) rfather
6 FROM
7 (SELECT test.country ,test.city,row_number() over (PARTITION BY test.country ORDER
BY test.city) rn
8 FROM test))
9 CONNECT BY PRIOR rchild=rfather START WITH rfather LIKE '%0')
10 GROUP BY country;
COUNTRY CITY
-------------------- -------
中国 上海,台北,香港
日本 大阪,东京
可谓是,7歪8搞,最后还是弄出来了,呵呵。