合并两列然后分组并排序

时间:2012-12-06 08:10:43

标签: sql group-by oracle11g

所有 我有以下表和数据,我想将loc1和loc2合并到一列中,并从loc列中删除重复值,然后根据group_no列对其进行分组,并根据group_val升序进行排序

drop table test;
create table test (loc1 number(9), loc2 number(9), group_no number(9),group_val number(9));
insert into test values(2,3,1,90);
insert into test values(2,9,1,10);
insert into test values(4,3,1,70);
insert into test values(6,8,2,20);
insert into test values(11,7,2,80);
insert into test values(20,15,2,70);
insert into test values(15,14,2,30);
insert into test values(21,31,3,50);
insert into test values(31,32,3,40);

预期结果是:

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

此代码来自Grish,但没有group_val,现在我添加

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


if can do it using dense_rank() over partition by group_val.

loc列将从上到下排序。累积到group_val列

regards

4 个答案:

答案 0 :(得分:1)

结果并不完全清楚你想要什么。也许这个?:

select loc, group_no 
from
(
    select loc1 as loc, group_no, group_val 
    from test

    union all

    select loc2 as loc, group_no, group_val
    from test
) t
group by group_no, loc
order by group_no asc, max(group_val) desc, loc asc ;

答案 1 :(得分:0)

select loc1, group_no 
from
 (
  select loc1, group_no, group_val from test
  UNION
  select loc2, group_no, group_val from test
 )
group by group_no , loc1
order by group_no, max(group_val), loc1

工作sqlfiddle

编辑:
正如Codo所说,你的数据存在冲突,所以你应该确定你的要求

答案 2 :(得分:0)

您可以尝试以下内容:

查询:

select distinct a.loc, a.group_no
from
(select distinct loc1 as loc, group_no
  from test
union all
select distinct loc2, group_no
  from test) as a
order by a.loc asc
;

结果:

LOC    GROUP_NO
2      1
3      1
4      1
6      2
7      2
8      2
9      1
11     2
14     2
15     2
20     2
21     3
31     3
32     3

答案 3 :(得分:0)

您的要求无法满足,因为它们包含冲突。如果查看前两行,您将在以下数据中看到结果(不使用 loc2 ):

loc | group_no | group_val
  2 |        1 |        90
  2 |        1 |        10

根据您的要求,它们是重复的,需要缩减为一行。但是,您使用什么group_val值进行排序:90或10?

如果您始终使用最小的group_val进行排序,则以下查询应该有效:

select t.loc, t.group_no from
(
    select loc1 as loc, group_no, group_val from test
    union
    select loc2 as loc, group_no, group_val from test
) t
group by t.loc, t.group_no
order by group_no, min(group_val);