I want to join two tables in a query extracting some information from each, but the second table requires a TOP 1:
This gets my list of people
SELECT [Clock no], [Card id], [Current pay cat], [Pay category]
FROM Employees EMP
WHERE [Clocked in flag] = 'Y'
Now for each of the people in that table I want to join to this query:
SELECT TOP 1 [Start time], Dated FROM [Work records] WR
WHERE WR.[Clock no] = XXXXXXXXX <- Clock no from first query
AND WR.Dated <= '2013-01-07' AND WR.[Open flag] = 'Y'
ORDER BY WR.[Dated] DESC, WR.[Start time] DESC
What I have so far is something like this, but I can’t seem to get it to work as soon as I add the ORDER By clause:
SELECT EMP.[Clock no], [Card id], [Current pay cat], [Pay category], WRTOP.[Start time], WRTOP.[Dated]
FROM Employees EMP
LEFT JOIN (
SELECT TOP 1 [Clock no], [Start time], Dated FROM [Work records] WR
WHERE WR.Dated <= '2013-01-07' AND WR.[Open flag] = 'Y'
ORDER BY WR.[Dated] DESC, WR.[Start time] DESC
) WRTOP
ON (EMP.[Clock no] = WRTOP.[Clock no])
WHERE EMP.[Clocked in flag] = 'Y'
The subquery returns one row, not necessarily for the right
Clock no. Only looking at the rightClock norequires a relation between the subquery and an outer table. That’s not allowed injoin.One way around that is a subquery in the
oncondition, like: