Sql 合并两列,然后按分组
我有下面的表格和数据,我想将loc1和loc2合并到一列中,并从loc列中删除重复值,然后根据group_no列对其进行分组Sql 合并两列,然后按分组,sql,group-by,oracle11g,Sql,Group By,Oracle11g,我有下面的表格和数据,我想将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); in
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
根据您的预期结果,您希望按
loc
分组,而不是group\u 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
您能显示预期的结果吗?但分组方式不是按升序排列的