如何只保留两列值的一个组合?
我有一个表(查询结果),如:
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
我该怎么做?
答案 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