2011-03-07 42 views
0

我有一個表:
1 | 5
2 | 4
3 | 3
4 | 2
5 | 1
(實際的表是有很多名字,我想要的是剛剛得到每一種組合的一組)
有沒有辦法得到最後沒有重複顛倒的行?
我只是想:
1 | 5
2 | 4
3 | 3個
行..我可以做到這一點的SQL?我可以得到在表格中不重複的行嗎?

回答

1

這會解決你的問題:

select * 
from MyTable 
where ColA <= ColB 

編輯:好吧,如果你有情況下,像20,5,那麼你可以使用這個:

with allpairs as (
    select ColA, ColB 
    from MyTable 
    where ColA <= ColB 

    union all 

    select ColB, ColA 
    from MyTable 
    where ColB < ColA 
) 
select distinct * 
from allpairs 
+0

可能,但是,如果有什麼在表中值分別爲20和5,其中沒有對應5和20. – DRapp 2011-03-07 11:43:39

+0

感謝您的回答,他們很有幫助! – dpoedq 2011-03-07 12:10:41

3

喜歡的東西:

select distinct(case when x<y then x||'|'||y else y||'|'||x end) from table; 

應該在Oracle上工作,在不同的db中使用相當於case。

測試:

select distinct(case when x<y then x||'|'||y else y||'|'||x end) from 
(select 1 x,2 y from dual 
union 
select 1 x,2 y from dual 
union 
select 1 x,3 y from dual 
union 
select 3 x,2 y from dual 
union 
select 2 x,1 y from dual 
); 

返回: 1 | 2 1 | 3 2 | 3

+0

就在我要去的地方......我唯一關心的人發佈是如果他/她想保留原始列作爲列,而不是一起管理。 – DRapp 2011-03-07 11:46:32

相關問題