Home > Enterprise >  Not filter correcting when I’m added case for the sql query
Not filter correcting when I’m added case for the sql query

Time:10-17

In my sql table, when I select data by using this query,

SELECT * FROM agreement_id, hierarchy_id, customer_no FROM rebate_agreement 
WHERE Customer_no = 'Kap-ST';

While I use the above query it filters the records as below,

agreement_id hierarchy_id customer_no
KAPA2 KHIE1 Kap-ST
KAPA3 KHIE1 Kap-ST
KAPA4 * Kap-ST

I want to filter 1st, hierarchy_id is '*' records & other records will display later. Hence I used the below query for it.

SELECT * FROM agreement_id, hierarchy_id, customer_no 
FROM rebate_agreement 
WHERE Customer_no = 'Kap-ST' 
ORDER BY CASE WHEN hierarchy_id = '*' THEN 1 ELSE 2 END;

Then it displays records as below,

agreement_id hierarchy_id customer_no
KAPA4 * Kap-ST
KAPA3 KHIE1 Kap-ST
KAPA2 KHIE1 Kap-ST

But I want to filter my records below format, (Display hierarchy_id ='*' records first and other records for the normal order)

agreement_id hierarchy_id customer_no
KAPA4 * Kap-ST
KAPA2 KHIE1 Kap-ST
KAPA3 KHIE1 Kap-ST

How I do it?

CodePudding user response:

ORDER BY CASE WHEN hierarchy_id = '*' THEN 1 ELSE 2 END, agreement_id

CodePudding user response:

You can take a look at the FIELD() function

  • Related