SQL过滤器列的组合

时间:2016-04-07 15:25:36

标签: sql oracle

如何只保留两列值的一个组合?

我有一个表(查询结果),如:

ID1 |ID2 |SomeNotImportantComun
1   |2   |A
2   |1   |A
3   |4   |C

对于第1行和第2行,ID1和ID2的组合是相同的[1,2]。我想继续其中一行。

ID1 |ID2 |SomeNotImportantComun
2   |1   |A
3   |4   |C

我该怎么做?

2 个答案:

答案 0 :(得分:3)

你可以尝试这样的事情:

with test(ID1, ID2, SomeNotImportantComun) as
(
select 1 ,2, 'A' from dual union all
select 2 ,1, 'A' from dual union all
select 3 ,4, 'C' from dual
)
select id1, id2, SomeNotImportantComun
from (
        select id1, id2, SomeNotImportantComun,
               row_number() over ( partition by least(id1, id2), greatest(id1, id2) order by id1 desc, id2 desc) as rank
        from test
     )
where rank = 1

在这里,您只为一行ID保留一行;您可以通过编辑order by子句

来决定要保留哪一个

答案 1 :(得分:1)

使用此查询查找存在对称对时不需要的行。

select t1.*
from tablename t1
join tablename t2 on t1.id1 = t2.id2 and t1.id2 = t2.id1 
and t1.somenotimpcol = t2.somenotimpcol
where t1.id1 < t1.id2

然后使用minus从原始表/查询结果中删除这些行。

select * from tablename
minus
select t1.*
from tablename t1
join tablename t2 on t1.id1 = t2.id2 and t1.id2 = t2.id1 
and t1.somenotimpcol = t2.somenotimpcol
where t1.id1 < t1.id2