Manan Kapoor
Manan Kapoor

Reputation: 677

Fetch single records based on priority via oracle in single query

I have a table in Oracle SQL as follows.

  Account_Id     Account_No              BS               STATUS
    1               10                    V                 ACTV
    2               11                    S                 DIS
    3               12                    E                NOTACTV
    4               10                    S                 DIS
    5               12                    E                 ACTV
    6               12                    V                 ACTV

I need to get the Account Number (one record) with below Mentioned priority.

 1) BS = V && STATUS = ACTV
 2) BS = S && STATUS = ACTV
 3) BS = E && STATUS = ACTV
 4) BS = V && STATUS = NOTACTV
 5) BS = S && STATUS = NOTACTV
 6) BS = E && STATUS = NOTACTV
 7) BS = V && STATUS = DIS
 8) BS = S && STATUS = DIS
 9) BS = E && STATUS = DIS

I tried using three sql queries with V and checking status ACTV and NOTACTV. I wanted to fetch the data in one sql query so as to optimize this.

How to do this??

Upvotes: 1

Views: 186

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

I think you want:

select t.*
from (select t.*
      from t
      order by (case status when 'ACTV' then 1 when 'NOTACTIV' then 2 WHEN 'DIS' then 3 else 4 end),
               (case BS when 'V' then 1 when 'S' then 2 when 'E' then 3 else 4 end)
    ) t
where rownum = 1;

If you are using Oracle 12c+, you can use fetch first and you don't need the subquery.

Here is a working version.

Upvotes: 2

Related Questions