I have, what I imagine is a standard SQL Design Pattern. I have two tables that I am trying to join. One has a Date, the other an Effective Date, and I want the last record of the second table with an Effective Date less than or equal to the Date of the first table.
The query I am using now goes something like:
SELECT *
FROM Timecard
LEFT JOIN Employee_Rate on Timecard.Employee=Employee_Rate.Employee
AND Employee_Rate.Effective_Date =
(
SELECT MAX(Effective_Date)
FROM Employee_Rate rate2
WHERE Employee_Rate.Employee=rate2.Employee
AND rate2.Effective_Date <=Timecard.Timecard_Date
)
This works just fine, and I have been doing it this way for a while. But I was wondering if there was a more efficient way of doing this. I am trying to increase performance on a couple of pretty complicated queries.
I am using SQL Server.
I would recommend a lateral join. This is a powerful feature that seems like a good fit for your use case:
select t.*, er.*
from timecard
outer apply (
select top (1) *
from employee_rate er
where er.employee = t.employee and er.effective_date <= t.timecard_date
order by er.effective_date desc
) er
For performance, consider an index on employee_rate(employee, effective_date)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.