我有下表指定员工分配。 Null表示当前分配:
|EmployeeNum|EmployeeAssignment|BeginDate |EndDate |
|1003 |Analyst |01/01/1990|02/04/2013|
|1002 |Coordinator |05/14/2000|06/01/2013|
|1003 |Trainer |07/28/2010|NULL |
|1004 |Janitor |08/09/2013|NULL |
|1005 |IT |09/02/2013|12/21/2013|
另一张表格指定时间段和付费时间:
|EmployeeNum| DatePaid |hworked|
|1003 | 05/11/2013|7.5 |
|1004 | 09/01/2013|8.25 |
|1005 | 09/15/2013|5.45 |
是否有一种方法可以使用SQL来比较两个表,以确定每个员工在工作时的分配?
答案 0 :(得分:2)
简单INNER JOIN
SELECT * FROM table1 t1
INNER JOIN table2 t2 ON t1.employeenum = t2.employeenum
只需在查询中选择您想要的任何内容
答案 1 :(得分:1)
我倾向于使用相关的子查询:
select t2.*,
(select EmployeeAssignment
from table1 t1
where t1.employeenum = t2.employeenum and
t2.datepaid between t1.begin_date and coalesce(t1.end_date, getdate())
) as EmployeeAssignment
from table2 t2;
编辑:
您也可以使用outer apply
做同样的事情。
实际上,根据您的数据结构,外部联接也应该起作用:
select t1.*, t2.EmployeeAssignment
from table1 t1 left join
table2 t2
on t1.employeenum = t2.employeenum and
t2.datepaid between t1.begin_date and coalesce(t1.end_date, getdate())