2

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.

GMB
  • 216,147
  • 25
  • 84
  • 135
  • 1
    Does this answer your question? [Get top 1 row of each group](https://stackoverflow.com/questions/6841605/get-top-1-row-of-each-group) – drf May 12 '20 at 23:34
  • 1
    Tip: The _actual execution plan_ is generally the place to start for performance issues with a query. – HABO May 13 '20 at 02:50

1 Answers1

1

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).

GMB
  • 216,147
  • 25
  • 84
  • 135