首页 > 解决方案 > 获取所有从未休假过的员工的姓名

问题描述

员工和 DaysTaken 表

在此处输入图像描述

嗨,我面临一个问题,即员工“John Smith”请“病假”和“假期”。这是我目前的答案

SELECT DISTINCT CONCAT(FirstName, ' ', MiddleName, ' ',  LastName) AS 'CompleteName' from Employee
RIGHT JOIN DaysTaken ON
Employee.EmployeeID =
DaysTaken.EmployeeID
WHERE (DaysTaken.vacationtype = 'sick day')

标签: sqlsql-server

解决方案


右外连接很难阅读,不建议使用它们。在您的查询中,您选择所有病假并外部加入相关员工。由于可能所有的病假都由员工使用,这与单纯的内部连接相同。

因此,您选择所有员工的病假天数。然后与DISTINCT您一起向每位生病的员工展示。这与您的请求标题所要求的完全不同。(并且加入所有这些行只是为了消除它们中的大多数,DISTINCT无论如何我都不会遵循这种方法。)

您的请求标题说

获取所有从未休假过的员工的姓名

为了获取员工姓名,您将从员工表中进行选择。您只需要满足条件的员工。条件最适合该WHERE子句。条件是该员工不存在休假条目。[NOT] EXISTS我们用or检查表中是否存在一行[NOT] IN

不存在

select concat_ws(' ', firstname, middlename, lastname) as complete_name
from employee e
where not exists
(
  select null
  from daystaken dt
  where dt.vacationtype = 'vacation'
  and dt.employeeid = e.employeeid
);

没有在

select concat_ws(' ', firstname, middlename, lastname) as complete_name
from employee
where employeeid not in
(
  select employeeid
  from daystaken
  where vacationtype = 'vacation'
);

在图像中只有vacationtype“假期”或“病假”的行。如果有其他条件,where vacationtype = 'vacation'可能仍然合适,但您可能还需要另一个条件,例如where vacationtype <> 'sick day'


推荐阅读