简体   繁体   English

如何基于同一列中的多个值过滤SQL查询

[英]How to filter SQL query based on multiple values in the same column

I need to write a query that pulls only employees who are missing their degrees entered into our ERP system. 我需要编写一个查询,仅将缺少学位的员工拉入我们的ERP系统。 For example, we have a table where their degrees are listed. 例如,我们有一个列出其学位的表格。

Employee ID   FName  LName  Degree
100           John   Smith  BA
200           Bill   Jones  BS
300           Alice  Waters BA
300           Alice  Waters MA
400           Joe    Lewis  MA

They would like me to pull from this table, only Joe Lewis because he doesn't have a bachelors degree entered in the system, but since he has a master's degree, the assumption is he also has a bachelor's, and someone just missed entering it into the system. 他们希望我从表中退出,只有乔·刘易斯(Joe Lewis),因为他没有在系统中输入学士学位,但是由于他具有硕士学位,所以假设他也有学士学位,而有人错过了进入进入系统。

I've tried using EXCEPT filtering on Bachelors degrees, however, that still yields 我试过对学士学位使用EXCEPT过滤,但是仍然可以

Employee ID   FName  LName  Degree
300           Alice  Waters MA
400           Joe    Lewis  MA

And I don't want Alice in the list because she has a bachelors degree coded into the system. 而且我也不希望Alice出现在名单中,因为她的系统中已经编码了学士学位。

Any thoughts on how I might approach this would be much appreciated. 我将如何处理此问题的任何想法将不胜感激。

If this is just for MA and BA, you can use conditional aggregation: 如果这仅适用于MA和BA,则可以使用条件聚合:

select empid, fname, lname
from t
group by empid, fname, lname
having sum(case when degree = 'BA' then 1 else 0 end) = 0 and
       sum(case when degree = 'MA' then 1 else 0 end) > 0;

Or, you can use exists : 或者,您可以使用exists

select t.*
from t
where degree = 'MA' and
      not exists (select 1
                  from t t2
                  where t2.empid = t.empid and t2.degree = 'BA'
                 );

You could go with a left join of the Masters subset against the Bachelors subset: 您可以将Masters子集与Bachelors子集的左联接放在一起:

select m.EmployeeId, m.FName, m.LName 
from      (select * from Employee where Degree in ('MA')) m
left join (select * from Employee where Degree in ('BA', 'BS')) b
on m.EmployeeId = b.EmployeeId
where b.EmployeeId is null

Maybe you should consider to use a query without subqueries... 也许您应该考虑使用没有子查询的查询...

SELECT E.EmployeeId, E.FName, E.LName 
FROM Employee AS E
LEFT JOIN Employee AS F ON (E.EmployeeId = F.EmployeeId AND F.Degree = 'BA')
WHERE E.Degree <> 'BA' AND F.EmployeeId IS NULL

Or (if BS must be considered as well) : 或(如果还必须考虑BS):

SELECT E.EmployeeId, E.FName, E.LName 
FROM Employee AS E
LEFT JOIN Employee AS F ON (E.EmployeeId = F.EmployeeId AND F.Degree IN('BA','BS'))
WHERE E.Degree <> 'BA' AND E.Degree <> 'BS' AND F.EmployeeId IS NULL

keep in mind subqueries are often slow, depending on how many row is concerned... 请记住,子查询通常很慢,具体取决于所关注的行数...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM