我对SQL非常陌生。我正在尝试连接两个表,tblEmployeeHours和tblWages。但是,工资表可以包含重复行。
下面是EmployeeHours表的一个片段:
x--------------x-------------x---------x-------x
| ReportDate | DeptCode | EmpID | Hours |
x--------------x-------------x---------x-------x
| 12/31/2017 | A | 112233 | 240 |
| 6/30/2018 | A | 112233 | 390 |
| 12/31/2017 | A | 224466 | 422 |
| 6/30/2018 | B | 334455 | 390 |
x--------------x-------------x---------x-------x工资表:
x----------x--------------x-------------x
| EmpID | CostCenter | HourlyWage |
x----------x--------------x-------------x
| 112233 | Engineering | 24.0 |
| 112233 | Engineering | 35.0 |
| 334455 | Field | 42.2 |
| 334455 | Field | 42.2 |
x----------x--------------x-------------x由于工资表中没有真正的唯一标识符,工资表中也没有每小时工资的生效日期(在本例中,我认为这是更大的问题),因此如何确保我正在用正确的时薪计算薪资支票金额(HourlyWage x小时)?我们假设工资是按时间顺序排列的。
例如,对于雇员112233,24.0是旧工资,35.0是最近的工资。我想用35.0美元/小时计算他2018年6月30日的薪水,用24美元计算他2017年12月31日的薪水。
我认为交叉申请也许能达到最高1 *的水平,但这仍然只会返回24美元的第一(旧)工资。
select e.ReportDate, e.EmpID, e.Hours, tw.HourlyWage
from tblEmployeeHours e
cross apply
( select top 1 *
from tblWages w
where w.EmpID = e.EmpID
) tw结果:
x--------------x----------x--------x------------x
| ReportDate | EmpID | Hours | HourlyWage |
x--------------x----------x--------x------------x
| 12/31/2017 | 112233 | 240 | 24 |
| 6/30/2018 | 112233 | 390 | 24 |
x--------------x----------x--------x------------x预期结果:
x--------------x----------x--------x------------x
| ReportDate | EmpID | Hours | HourlyWage |
x--------------x----------x--------x------------x
| 12/31/2017 | 112233 | 240 | 24 |
| 6/30/2018 | 112233 | 390 | **35** |
x--------------x----------x--------x------------x发布于 2018-06-15 20:34:01
SQL表表示无序集。没有订单。没有“时间顺序”或其他顺序。
这种方法:
select e.ReportDate, e.EmpID, e.Hours, tw.HourlyWage
from tblEmployeeHours e cross apply
(select top 1 *
from tblWages w
where w.EmpID = e.EmpID
) tw;任意选择任意匹配行。你真的需要:
select e.ReportDate, e.EmpID, e.Hours, tw.HourlyWage
from tblEmployeeHours e cross apply
(select top 1 *
from tblWages w
where w.EmpID = e.EmpID
order by w.effective_date -- or whatever column goes here
) tw;如果您有identity列或dateCreated列,则可以使用选择(例如)。
您可以假设工资总是上涨,并使用order by w.HourlyWage desc,但对于这个应用程序来说可能不是这样。
https://stackoverflow.com/questions/50882233
复制相似问题