选择优先顺序

时间:2015-02-02 10:16:55

标签: sql oracle select

这是我的桌子CAR

+------+--------+---------+
| id   | model  | color   |
+------+--------+---------+
| 1    | bmw    | blue    |
| 2    | bmw    | red     |
| 3    | bmw    | null    |
| 4    | porsche| null    |
| 5    | porsche| red     |
| 6    | vw     | orange  |
| 7    | car    | null    |
+------+-------+----------+

如何选择具有此优先级颜色的所有区别模型:

  1. blue
  2. red
  3. null或其他颜色......
  4. 查询结果如下:

    +------+--------+
    | id   | model  |
    +------+--------+
    | 1    | bmw    |
    | 5    | porsche|
    | 6    | vw     |
    | 7    | car    |
    +------+--------+
    

1 个答案:

答案 0 :(得分:2)

您可以使用row_number()分析函数设置颜色的顺序,然后对row_number = 1进行过滤:

with car as (select 1 id, 'bmw' model, 'blue' colour from dual union all
             select 2 id, 'bmw' model, 'red' colour from dual union all
             select 3 id, 'bmw' model, null colour from dual union all
             select 4 id, 'porsche' model, null colour from dual union all
             select 5 id, 'porsche' model, 'red' colour from dual union all
             select 6 id, 'vw' model, 'orange' colour from dual union all
             select 7 id, 'car' model, null colour from dual union all
             select 8 id, 'vw' model, 'purple' colour from dual)
select id,
       model
from   (select id,
               model,
               colour,
               row_number() over (partition by model 
                                  order by decode(colour, 'blue', 1, 'red', 2, 3), colour) rn
        from   car)
where  rn = 1
order by id;

    ID MODEL  
---------- -------
         1 bmw    
         5 porsche
         6 vw     
         7 car