我在MS-SQL Server中有Node varchar(25)
列。
可能的值是
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。
答案 0 :(得分:1)
您将两个数据压入一列。这不太理想。所以我的解决方案首先要纠正这个问题:
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.
答案 1 :(得分:0)
select distinct(Node) from YOUR_TABLE;
这是一个带有示例的SQLfiddle:http://www.sqlfiddle.com/#!4/76484/2
我回答了oracle,因为这个问题被标记为oracle。对于MS-Server,它可能是同样的事情......
答案 2 :(得分:0)
另一种方法。与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