嗨,我需要根据where子句中满足的条件对行进行排名。所以我写了查询
select 1 as priority, usr_fname, usr_lname from core_users where usr_fname = 'John' and usr_lname = 'smith' and suburb = '0162'
union
select 2 as priority, usr_fname, usr_lname from core_users where usr_fname = 'John' and usr_lname = 'smith' and usr_title = 'Mr'
union
select 3 as priority, usr_fname, usr_lname from core_users where usr_fname = 'John' and usr_lname = 'smith'
现在我的TL坚持我可以在这里使用sql rank()/ row_number()。有人可以指导吗?
答案 0 :(得分:2)
如果您确实使用row_number()
,则可以获取3个以上的值:
select usr_fname, usr_lname,
row_number() over (case when suburb = '0162' then 1
when usr_title = 'Mr' then 2
else 3
end) as priority
from core_users
where usr_fname = 'John' and usr_lname = 'smith' ;
您可以使用dense_rank()
而不是row_number()
获得同等的优先级。但是,如果数据中没有全部显示三个组,则数字将为“ 1”或“ 1”和“ 2”。
但是,更简单的版本仅使用case
表达式即可满足您的要求:
select usr_fname, usr_lname,
(case when suburb = '0162' then 1
when usr_title = 'Mr' then 2
else 3
end) as priority
from core_users
where usr_fname = 'John' and usr_lname = 'smith' ;
您的版本多次返回同一行-针对它匹配的每个优先级一次。这只会返回每行一次,我猜这是您的实际意图。