There are multiple solutions for this, in the solution below I used CTEs (common table expressions) to split the work in logical units. cteVarTimes
selects all valid combinations of Variables
and Timeaccount
, then cteMostRecent
selects the latest for the user. In the main select I combine this with the information from Qualifications
and Rapportcostrate
.
This solution doesn't work if you need to be able to return rows for all users. In that case you would need to replace cteMostRecent
with a query that selects rows using a group wise maximum of VarValidFrom
and TiaDate
per user.
WITH cteVarTimes AS (
SELECT v.VarUserId as UserId, v.VarQuaId, tia.TiaValue, tia.TiaDate, v.VarValidFrom
FROM Variables v
INNER JOIN Timeaccount tia
ON tia.TiaUserId = v.VarUserId
WHERE tia.TiaDate >= v.VarValidFrom
),
cteMostRecent AS (
SELECT UserId, VarQuaId, TiaValue, VarValidFrom
FROM cteVarTimes
WHERE UserId = 1 -- Parameter in real use
ORDER BY VarValidFrom DESC, TiaDate DESC
ROWS 1
)
SELECT RcrRate, TiaValue, VarValidFrom
FROM cteMostRecent a
INNER JOIN Qualifications q
ON q.QuaId = a.VarQuaId
INNER JOIN Rapportcostrate rcr
ON rcr.RcrId = q.QuaRcrId