Oracle SELECT查询查找最小的不同分隔字符串

时间:2017-09-14 03:29:12

标签: sql oracle

我有下表

C1      |  Path
--------|-----------
T1      | T0/T1
T2      | T0/T1/T2
T3      | T0/T1/T2/T3
X1      | T0/X0/X1
T2      | T0/X0/X1/T2
T3      | T0/X0/X1/T2/T3
T3      | T0/Y0/Y1/Y2/T3
Y3      | T0/X0/X2/Y3
Y4      | T0/X0/X2/Y3/Y4

我需要编写q查询或代码,它应返回最小的不同分隔字符串,如下所示

C1      |  Path
--------|-----------
T1      | T0/T1
X1      | T0/X0/X1
T3      | T0/Y0/Y1/Y2/T3
Y3      | T0/X0/X2/Y3

Ex:T0/T1T0/T1/T2T0/T1/T2/T3的子字符串。
T0/Y0/Y1/Y2/T3不是任何其他字符串的子字符串。它是截然不同的。

你能帮我在oracle中写这个查询吗

2 个答案:

答案 0 :(得分:2)

尝试:

SELECT t1.*
FROM Table1 t1
LEFT JOIN Table1 t2
ON t1.Path <> t2.Path
   AND t1.path LIKE '%'||t2.Path||'%' 
WHERE t2.c1 IS NULL

演示:http://sqlfiddle.com/#!4/a3f87/3

| C1 |           PATH |
|----|----------------|
| T1 |          T0/T1 |
| X1 |       T0/X0/X1 |
| T3 | T0/Y0/Y1/Y2/T3 |
| Y3 |    T0/X0/X2/Y3 |

答案 1 :(得分:1)

此查询有效http://sqlfiddle.com/#!4/bf32e/19

With X as
(select 'T0/T1' c1 from dual
union
select 'T0/T1/T2' c1 from dual
union
select 'T0/T1/T2/T3' c1 from dual
union
select 'T0/X0/X1' c1 from dual
union
select 'T0/X0/X1/T2' c1 from dual
union
select 'T0/X0/X1/T2/T3' c1 from dual
union
select 'T0/Y0/Y1/Y2/T3' c1 from dual
union
select 'T0/X0/X2/Y3' c1 from dual
union
select 'T0/X0/X2/Y3/Y4' c1 from dual),
Y as (
select distinct X1.C1 YC1 from X X1, X X2
where X1.C1 like '%'||X2.C1||'%' and X1.C1<>X2.C1)
select * from X where not exists
(select 1 from Y where YC1=X.C1)