使用SQL Server查询从考勤记录表和员工表中获取空值?

时间:2015-07-27 05:27:48

标签: sql-server

我有查询提取这样的数据:

if let

结果如下:

enter image description here

虽然我已经包含了SELECT e.EmpName, d.DepartmentName, l.EnrollNumber, v.VerifyModeName, CAST(PunchTime as DATE)Check_Date,MIN(CAST(PunchTime as Time))[TimeIN], MAX(Cast(PunchTime as Time))[TimeOUT], RIGHT('0' + CAST(DATEDIFF(SECOND, MIN(CAST(PunchTime as Time)), MAX(Cast(PunchTime as Time))) / 3600 AS VARCHAR),2) + ':' + RIGHT('0' + CAST((DATEDIFF(SECOND, MIN(CAST(PunchTime as Time)), MAX(Cast(PunchTime as Time))) / 60) % 60 AS VARCHAR),2) + ':' + RIGHT('0' + CAST(DATEDIFF(SECOND, MIN(CAST(PunchTime as Time)), MAX(Cast(PunchTime as Time))) % 60 AS VARCHAR),2) as Duration FROM Department d, VerifyModes v, Employee e FULL OUTER JOIN AttLog l ON e.EnrollNumber=l.EnrollNumber WHERE e.DeptID = d.Id AND l.VerifyMode = v.VerifyModeId GROUP BY e.EmpName, d.DepartmentName, l.EnrollNumber, v.VerifyModeName, CAST(PunchTime as DATE) ORDER BY Check_Date 条件。

如果我只使用:

full outer join

结果显示select e.EmpName, l.PunchTime from Employee e full outer join AttLog l on e.EnrollNumber = l.EnrollNumber Employee NULL

enter image description here

那么,如何修复上述查询以获取包含PunchTime NULL的结果?

然后,当我添加日期条件时,查询仍然不会再次显示NULL。如何纠正?

PunchTime

enter image description here

1 个答案:

答案 0 :(得分:1)

请尝试使用LEFT JOIN

SELECT 
    e.EmpName,
    d.DepartmentName,
    l.EnrollNumber,
    v.VerifyModeName,
    CAST(PunchTime as DATE)Check_Date,MIN(CAST(PunchTime as Time))[TimeIN], MAX(Cast(PunchTime as Time))[TimeOUT],
        RIGHT('0' + CAST(DATEDIFF(SECOND, MIN(CAST(PunchTime as Time)), MAX(Cast(PunchTime as Time))) / 3600 AS VARCHAR),2) + ':' +
        RIGHT('0' + CAST((DATEDIFF(SECOND, MIN(CAST(PunchTime as Time)), MAX(Cast(PunchTime as Time))) / 60) % 60 AS VARCHAR),2)  + ':' +
        RIGHT('0' + CAST(DATEDIFF(SECOND, MIN(CAST(PunchTime as Time)), MAX(Cast(PunchTime as Time))) % 60 AS VARCHAR),2) as Duration
FROM Department d    
INNER JOIN Employee e
    ON e.DeptID = d.Id
LEFT JOIN AttLog l 
    ON e.EnrollNumber = l.EnrollNumber
LEFT JOIN VerifyModes
    ON l.VerifyMode = v.VerifyModeId 
GROUP BY 
    e.EmpName, d.DepartmentName, l.EnrollNumber, v.VerifyModeName, CAST(PunchTime as DATE)
ORDER BY Check_Date

注意:Avoid using old-style JOIN syntax.

编辑: 而不是将日期比较放在WHERE子句中,而是将其置于JOIN条件中:

LEFT JOIN Attlog l
    ON e.DeptID = d.Id
    AND cast(l.PunchTime as Date) between '2015-07-22' and '2015-07-22'

将比较放在WHERE子句中,将查询转换为INNER JOIN,从而删除NULL行。