我Node varchar(25)
在 MS-SQL Server 中有列。可能的值为
node
-----
D-C
C-B
B-A
B-C
B-E
C-A
A-B
A-C
C-D
etc.
我想从中检索不同的组合。例如:
node
----
D-C
C-B
B-A
B-E
C-A
请为此告诉SQL。
我Node varchar(25)
在 MS-SQL Server 中有列。可能的值为
node
-----
D-C
C-B
B-A
B-C
B-E
C-A
A-B
A-C
C-D
etc.
我想从中检索不同的组合。例如:
node
----
D-C
C-B
B-A
B-E
C-A
请为此告诉SQL。
您将两条数据压入一列。这并不理想。所以我的解决方案首先必须纠正这个:
SQL> create table mytable (node)
2 as
3 select 'D-C' from dual union all
4 select 'C-B' from dual union all
5 select 'B-A' from dual union all
6 select 'B-C' from dual union all
7 select 'B-E' from dual union all
8 select 'C-A' from dual union all
9 select 'A-B' from dual union all
10 select 'A-C' from dual union all
11 select 'C-D' from dual
12 /
Table created.
SQL> with structured_data as
2 ( select regexp_substr(node,'[^-]+',1,1) startnode
3 , regexp_substr(node,'[^-]+',1,2) endnode
4 from mytable
5 )
6 select distinct least(startnode,endnode) startnode
7 , greatest(startnode,endnode) endnode
8 from structured_data
9 /
STARTNODE ENDNODE
--------- -------
B E
A C
A B
C D
B C
5 rows selected.
select distinct(Node) from YOUR_TABLE;
这是一个带有示例的 SQLfiddle:http ://www.sqlfiddle.com/#!4/76484/2
我回答了 oracle,因为这个问题被标记为 oracle。对于 MS-Server,它可能是同样的事情......
另一种方法。非常类似于 Rob van Wijk 在使用greatest()
和least()
函数方面发布的内容,但没有调用正则表达式函数。我们可以计算最大和最小列值及其反转值 - 函数返回的值reverse()
:
注意: reverse()
函数是未记录的函数。不要在生产应用程序中使用它。
with t1(col) as(
select 'D-C' from dual union all
select 'C-B' from dual union all
select 'B-A' from dual union all
select 'B-C' from dual union all
select 'B-E' from dual union all
select 'C-A' from dual union all
select 'A-B' from dual union all
select 'A-C' from dual union all
select 'D-C' from dual
)
select res_1 /* as well/or we can choose res_2 */
from (select distinct
greatest(col, reverse(col)) as res_1
, least(col, reverse(col)) as res_2
from t1)
结果:
RES_1
-----
D-C
B-A
C-A
C-B
E-B
或#2
select col
from ( select col
, row_number() over(partition by greatest(col, reverse(col))
, least(col, reverse(col))
order by col) as rn
from t1
)
where rn = 1
结果:
COL
---
A-B
A-C
B-C
D-C
B-E