2012-12-06 65 views
0

我有以下表和數據,我想合併一列中的loc1和loc2,並刪除loc列中的重複值,然後根據group_no列對其進行分組。合併兩列然後組合

drop table test; 
create table test (loc1 number(9), loc2 number(9), group_no number(9)); 
insert into test values(2,3,1); 
insert into test values(2,9,1); 
insert into test values(4,3,1); 
insert into test values(6,8,2); 
insert into test values(11,7,2); 
insert into test values(20,15,2); 
insert into test values(15,14,2); 
insert into test values(21,31,3); 
insert into test values(31,32,3); 

預期的結果是:

loc group_no 
2  1 
3  1 
9  1 
4  1 
6  2 
8  2 
11  2 
20  2 
15  2 
21  3 
31  3 
32  3 

問候

+0

您能展示預期的結果嗎? –

回答

1

根據您所需要的結果,您可以通過loc而不是group_no想組。

select t.loc, max(t.group_no) 
(
    select loc1 as loc, group_no from test 

    union 

    select loc2 as loc, group_no from test 
) t 
group by t.loc 
order by 2,1 
+0

但是group by不是升序 – user1873093

+0

只是添加'order by' –