SQL:根据优先级(层次结构)和其他列的可用性选择唯一列

时间:2017-06-27 14:51:11

标签: sql select conditional-statements hierarchy

我正在使用Oracle SQL Developer版本4.0.3.16 我有一张这样的桌子:

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

我想选择每个名称类别中具有最小序列号而不是null值的行。 Aka结果将是

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

如果名称没有可用值,则将值显示为null,且序列号最小。

2 个答案:

答案 0 :(得分:1)

如果您的数据库支持元组您可以使用带有子选择的元组和in子句

  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

或其他人DB加入

  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

答案 1 :(得分: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获取最小Name的行,其中Value不为空。如果名称的所有Value都为null,则获取该名称最高Sequence的行。

相关问题