2017-09-06 38 views
1

我在oracle 11g數據庫上運行sql語句。輸出是像一些加入以下(還有其他列,但重要的列是這些的)如何在oracle數據庫上使用case..when

 
id | document  | address 
---+----------------+-------------- 
1 | identity_card | hudson street 
1 | driver_licence | hudson street 
1 | passport  | hudson street 
1 | identity_card | mike street 
1 | driver_licence | mike street 
1 | passport  | mike street 
2 | driver_licence | laura street 
2 | passport  | laura street 
3 | passport  | amy street 
3 | identity_card | bug street 
3 | identity_card | apple street 
3 | passport  | bug street 
4 | driver_licence | 16th street 
5 | identity_card | 21st street 

但是我想這是類似的東西:

 
id | document  | address 
---+----------------+-------------- 
1 | identity_card | hudson street 
1 | identity_card | mike street 
2 | passport  | laura street 
3 | identity_card | bug street 
3 | identity_card | apple street 
4 | driver_licence | 16th street 
5 | identity_card | 21st street 

爲你可能看到我正在查看每個ID,如果ID有identity_card作爲文檔,我拿這行。如果沒有身份證但有護照,我拿那條線,如果沒有身份證和護照,我拿driver_licence。

我該怎麼做這樣的事情?我想我可以使用「case ... when」,但我無法弄清楚如何將「case ... when」應用於我的案例。

在此先感謝!

回答

3

一種方法是使用dense_rank()

select t.* 
from (select t.*, 
      dense_rank() over (partition by id 
           order by case when document = 'identity_card' then 1 
               when document = 'passport' then 2 
               when document = 'drivers_license' then 3 
               else 4 
             end) as seqnum 
     from t 
    ) t 
where seqnum = 1; 
1

要將現有查詢,添加:

, rank() over (partition by id order by case document when 'identity_card' then 1 
                 when 'passport'  then 2 
                 when ...................... 
                 ........................... 
             end) as rnk 

然後,在外部查詢,選擇一切,並添加

where rnk = 1