I'm trying to rewrite some old SQL queries that look particularly awful. I am wondering if there is a more efficient way to prioritize values in a where statement for order of precedence. Basically the table contains multiple email_code records per user but I want to prioritize based on what records are preferred. In this case if the email_code is WORK it should be selected. But if there is no WORK record then HOME should be selected, and so on. Here is an example of what I am working with. There has to be a more graceful way to do this...?
select
*
from
email m
where
status_ind='A'
and decode(email_code, 'WORK',1,
'HOME',2,
'ALT1',3,
'ALT2',4,5) = (select
min(decode(email_code, 'WORK',1,
'HOME',2,
'ALT1',3,
'ALT2',4,5))
from
email
where
email_uid = m.email_uid
and status_ind='A');
Try:
SELECT * FROM (
SELECT e.*,
dense_rank() over (PARTITION BY user_id
ORDER BY CASE email_code
WHEN 'WORK' THEN 1
WHEN 'HOME' THEN 2
WHEN 'ALT1' THEN 3
WHEN 'ALT2' THEN 4
ELSE 5
END ) As priority
FROM emails e
WHERE status_ind='A'
)
WHERE priority = 1