加入两张桌子并获得所有员工姓名和出席情况

时间:2017-09-05 12:50:30

标签: sql join

我有2张桌子 首先是员工,第二是出勤

员工表: -

enter image description here

出勤表: -

enter image description here

在AttDate =' 2017-09-05'

中,只有3名员工参加了考勤表。

我使用此查询加入这些表: -

select EmpName,Attendance from Employee Left join Attendance on Employee.EmpId = Attendance.refId where AttDate ='2017-09-05' 

它显示了这个输出: -

enter image description here

但是我需要这个输出(出勤率没有进入考勤表的员工也会出现空出勤率): -

enter image description here

我应该在查询中更改什么才能获得此输出?

2 个答案:

答案 0 :(得分:1)

如果您同时加入日期值,则不会消除结果集:

select EmpName,Attendance 
from Employee Left join Attendance on Employee.EmpId = Attendance.refId and AttDate ='2017-09-05' 

您还将获得当天没有参加的员工。 查看this answer以获取更多信息,了解where条款与on条款的条件之间的区别。

答案 1 :(得分:0)

你用WHERE来限制它,所以那天没有参加课程的两位EmpID不会出现。

您可以将where更改为:

WHERE AttDate = '2017-09-05' or AttDate is null;

但这会带回所有在日期中为空的结果