2017-06-27 242 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