sql查询在sql server中查找带有日期的缺席列表

时间:2015-01-07 12:13:51

标签: sql sql-server database

我有两个出勤表。一个是employeelist,另一个是attendence_infoEmployeelist contain Emp_Id and Emp_nameAttendance_info is Emp_Id, Date。如下:

Emp_ID      Date
----------- -----------------------
1         2014-12-11 00:00:00.000
2         2014-12-11 00:00:00.000
4         2014-12-11 00:00:00.000
5         2014-12-11 00:00:00.000
2         2014-12-10 00:00:00.000
4         2014-12-10 00:00:00.000
5         2014-12-10 00:00:00.000
1         2014-12-09 00:00:00.000
2         2014-12-09 00:00:00.000
3         2014-12-09 00:00:00.000

这里每个日期都有一些id不存在。我想找出所有缺少日期的列表。请通过Sql server查询帮助找到它。我想要的输出应该如下:

   absentId       Date
    3         2014-12-11 00:00:00.000
    1         2014-12-10 00:00:00.000
    3         2014-12-10 00:00:00.000
    4         2014-12-09 00:00:00.000
    5         2014-12-09 00:00:00.000

3 个答案:

答案 0 :(得分:0)

select e.Emp_ID as absentId,a.Date as date
from employeelist e
join attendence_info a
on e.Emp_ID=a.Emp_ID
order by a.Date

答案 1 :(得分:0)

您可以通过生成所有员工和日期的列表,然后删除员工所在的列表来执行此操作。这基本上是cross joinleft join

select el.emp_id, d.date
from (select distinct date from Attendance_info) d cross join
     employeelist el left join
     Attendance_info ai
     on ai.date = d.date and ai.emp_id = el.emp_id
where ai.emp_id is null;

答案 2 :(得分:0)

DECLARE @StartDate DATETIME = '2014-12-09'
DECLARE @EndDate DATETIME = '2014-12-11'

;WITH MyCte ([Date])
AS
(
    SELECT  [Date] = @StartDate
    UNION ALL
    SELECT  DATEADD(DAY, 1, [Date]) FROM MyCte WHERE [Date] < @EndDate
)
,EmployeeList ([EmpID], [Date])
AS
(
    SELECT 1, '2014-12-11 00:00:00.000' UNION
    SELECT 2, '2014-12-11 00:00:00.000' UNION
    SELECT 4, '2014-12-11 00:00:00.000' UNION
    SELECT 5, '2014-12-11 00:00:00.000' UNION
    SELECT 2, '2014-12-10 00:00:00.000' UNION
    SELECT 4, '2014-12-10 00:00:00.000' UNION
    SELECT 5, '2014-12-10 00:00:00.000' UNION
    SELECT 1, '2014-12-09 00:00:00.000' UNION
    SELECT 2, '2014-12-09 00:00:00.000' UNION
    SELECT 3, '2014-12-09 00:00:00.000'
)
SELECT  DISTINCT E.[EmpID], M.[Date]
FROM    EmployeeList E
CROSS APPLY (SELECT [Date] FROM MyCTE WHERE [Date] NOT IN (SELECT [Date] FROM EmployeeList WHERE EmpID = E.EmpID)) M