2017-06-27 246 views
1

我使用的Oracle SQL Developer版本4.0.3.16 其他列的唯一的列和可用性我有这样的一个表:SQL:选择基于优先级(层次)

Name | Value | Sequence 
------ | ------ | ------ 
A  | 12  | 0 
A  | 15  | 1 
A  | 11  | 2 
B  | null | 0 
B  | 5  | 2 
B  | 7  | 3 
C  | 12  | 1 

我要选择每个名称类别中具有最小序列号且不为空值的行。结果将是

Name | Value | Sequence 
------ | ------ | ------ 
A  | 12  | 0 
B  | 5  | 2 
C  | 12  | 1 

如果名称没有可用值,则显示值为空,序号最小。

+0

您正在使用哪些rdbms?产品和版本。 –

+0

Oracle SQL Developer版本4.0.3.16 – Deb

回答

1

如果你的数据库支持,元组,您可以使用在第一个元组和一个子查询

select * from 
    my_table 
    where (name, sequnce) in ( 
     select Name, min(sequence) 
     from my_table 
     group by name 
     where value is not null) 
    where Value is not null 

或其他数据库联接

select a.* from 
    my_table a 
    INNER join ( 
     select Name, min(sequence) as min_seq 
     from my_table 
     group by name 
     where value is not null) t on a.name = t.name 
          and a.sequence = t.min_seq 
          and a.name is not null 
0

如果我理解正确的,你需要这样的:

with the_table(Name , Value , Sequence) as(
select 'A',12  , 0 from dual union all 
select 'A',15  , 1 from dual union all 
select 'A',11  , 2 from dual union all 
select 'B',null , 0 from dual union all 
select 'B',5  , 2 from dual union all 
select 'B',7  , 3 from dual union all 
select 'C',12  , 1 from dual 
) 

-- below is actual query: 

select the_table.* from the_table 
inner join (
    select Name, min(case when Value is not null then Sequence end) as mn, max(Sequence) as mx 
    from the_table 
    group by Name 
) t 
on the_table.Name = t.Name and the_table.Sequence = coalesce(t.mn, t.mx) 

为每获取具有最小行Sequence 0,其中Value不为空。如果所有Value对于名称均为空,则获取该名称的最高行Sequence