我有一张如下表格。
colA colB
12345 NHS,CDE,BCD
12345 NHS,ABC,DEF
需要以下列格式显示数据
colA colB
12345 NHS,ABC,BCD,CDE,DEF
我需要通用的解决方案来删除重复的NHS,它首先出现,然后按字母顺序排列其余的单词。
答案 0 :(得分:2)
首先,永远不要使用 WM_CONCAT ,因为它没有记录,并且在最新版本12c中不再可用。请参阅Why not use WM_CONCAT function in Oracle?和Why does the wm_concat not work here?
由于您使用的是11g,因此可以使用 LISTAGG 。
以下查询会执行以下操作:
例如,
SQL> WITH DATA AS(
2 SELECT 12345 colA, 'NHS,CDE,BCD' colB FROM dual UNION ALL
3 SELECT 12345 colA, 'NHS,ABC,DEF' colB FROM dual
4 )
5 SELECT cola,
6 listagg(colb, ',') WITHIN GROUP(
7 ORDER BY
8 CASE colb
9 WHEN 'NHS'
10 THEN 1
11 ELSE 2
12 END, colb) colb
13 FROM
14 (SELECT DISTINCT cola,
15 trim(regexp_substr(colb, '[^,]+', 1, LEVEL)) colb
16 FROM DATA
17 CONNECT BY LEVEL <= regexp_count(colb, ',')+1
18 ORDER BY colb
19 )
20 GROUP BY cola
21 /
COLA COLB
---------- ------------------------------
12345 NHS,ABC,BCD,CDE,DEF
编辑正如@AlexPoole指出的那样,显式排序缺失,之前的查询(参见编辑历史)依赖于值的不同排序。
答案 1 :(得分:0)
WITH t AS
(SELECT col1,wm_concat(col2) AS col2 FROM test1 GROUP BY col1
) , t1 AS
( SELECT DISTINCT col1, regexp_substr(col2, '[^,]+', 1, rownum) names
FROM t
CONNECT BY rownum <= LENGTH(regexp_replace(col2, '[^,]'))+1
ORDER BY names
)
SELECT col1,wm_concat(names) AS names FROM t1 GROUP BY col1