首页 > 解决方案 > 获取 sql 结果中的预定义记录,而不管它是否存在

问题描述

我有一个表,其中员工姓名中有重复值,但描述是唯一的。我只想选择我在脚本中预定义了名称的 5 名员工。

select
Employee in (John A, Ronny C, Harry D, David R, Alison R)
from Employee table 
where employee in (John A, Ronny C, Harry D, David R, Alison R) and description like "% Manager %"

在上面的脚本中,如果 Johan A 不是经理,那么他的记录将不会出现,我希望他的名字出现在结果中,但描述栏中应该有“NULL”

标签: sql

解决方案


如果我理解正确,您可以使用聚合:

select name,
       max(case when description like '%Manager%' then description end) as manager_description
from employee
where name in ('John A', 'Ronny C', 'Harry D', 'David R', 'Alison R')
group by name;

这将返回表中所有匹配的名称。如果有“经理”描述,则返回该描述。如果没有,那么NULL


推荐阅读