检查列中的 ID' 在同一表的另一列中是否没有具体值

Check that an ID' in a Column have no particulate value in another column at the same tables

我的薪水 table 带有 salarySumId、salaryYear,我想进行 select 查询以查找根本没有 2020-01-01 的 salarySumId。

我的查询看起来像这样

select distinct  salarySumId, salaryYear 
from Salary 

这个问题return是这样的

salarySumId     salaryYear 
-----------     ------------
4593086         2019-01-01 
4593093         2018-01-01 
4593093         2019-01-01 
4593093         2020-01-01 
4593094         2019-01-01 
4593095         2018-01-01 
4593095         2019-01-01 
4593095         2020-01-01 
4593096         2017-01-01 
4593096         2018-01-01 
4593096         2019-01-01 
4593096         2020-01-01 

当我编写如下过滤 2020-01-01 的查询时:

select distinct  salarySumId, salaryYear 
from Salary 
where Salary.InsuranceYear < '2020-01-01'

alarySumId      salaryYear 
-----------     ------------
4593086         2019-01-01 
4593093         2018-01-01 
4593093         2019-01-01 
4593094         2019-01-01 
4593095         2018-01-01 
4593095         2019-01-01 
4593096         2017-01-01 
4593096         2018-01-01 

实际上我只想查询 return (4593086, 4593094) 因为他们根本没有 2020-01-01 的 salaryYear 值。

如何重新编写查询来做到这一点?

做一个GROUP BY。在 HAVING 子句中使用 case 表达式来计算 2020-01-01 行数。

select salarySumId
from Salary
group by salarySumId
having sum(case when salaryYear = '2020-01-01' then 1 else 0 end) = 0

您可以使用 not exists :

select s.*
from Salary s
where not exists (select 1 
                  from Salary s1 
                  where s1.salarySumId = s.salarySumId and 
                        s1.salaryYear = '2020-01-01'
                );