[英]How to filter data in SQL based on the availablity of values (in a sequence) in a particular column?
I don't know if I am framing the question correctly but let me summarise the problem by giving an example.我不知道我是否正确地提出了这个问题,但让我举个例子来总结一下这个问题。
SELECT *
FROM EMPLOYEE
WHERE EMPLOYEE.TYPE IN ('CEO', 'MANAGER', 'LEAD', 'DEVELOPER')
Here you can see that all the rows will be returned where the values fall inside the mentioned values.在这里,您可以看到将返回值落在上述值内的所有行。
What I want is that if 'CEO' exists in the table, return the records with CEO only.我想要的是,如果表中存在“CEO”,则仅返回带有 CEO 的记录。 If not, then return the records with 'MANAGER' and so on.
如果没有,则返回带有“MANAGER”的记录,依此类推。
Based on a sequencing logic, only one record should be returned (based on availability).根据排序逻辑,应仅返回一条记录(基于可用性)。
Also this is a part of a larger SQL query so if there's a solution where this can be achieved in a single line or two will be helpful.这也是更大的 SQL 查询的一部分,所以如果有一个解决方案可以在一两行中实现这一点将会有所帮助。
You can use rank()
:您可以使用
rank()
:
select e.*
from (select e.*,
rank() over (order by case e.type when 'CEO' then 1 when 'MANAGER' then 2 when 'LEAD' then 3 WHEN 'DEVELOPER' then 4 else 5 end) as seqnum
from e
where e.TYPE in ('CEO','MANAGER','LEAD','DEVELOPER')
) e
where seqnum = 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.