0

我有以下表和数据,我想将 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

4 回答 4

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 ;
于 2012-12-06T08:26:15.977 回答
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 提到的,你的数据有冲突,所以你应该明确你的要求

于 2012-12-06T08:26:23.907 回答
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
于 2012-12-06T08:28:06.477 回答
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);
于 2012-12-06T08:32:29.577 回答