Question

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'
Was it helpful?

Solution

The subquery returns one row, not necessarily for the right Clock no. Only looking at the right Clock no requires a relation between the subquery and an outer table. That's not allowed in join.

One way around that is a subquery in the on condition, like:

SELECT  EMP.[Clock no]
,       EMP.[Card id] 
,       EMP.[Current pay cat]
,       EMP.[Pay category]
,       WR.[Start time]
,       WR.[Dated]
FROM    Employees EMP 
JOIN    [Work records] WR 
ON      WR.[Open flag] = 'Y' 
        AND WR.[Clock no] = EMP.[Clock no]
        AND WR.Dated =
        (
        SELECT  max(Dated)
        FROM    [Work records] WR2
        WHERE   WR2.[Open flag] = 'Y'
                AND WR2.[Clock no] = EMP.[Clock no]
                AND WR2.Dated <= '2013-01-07'
        )
        AND WR.[Start time] =
        (
        SELECT  max([Start time])
        FROM    [Work records] WR3
        WHERE   WR3.[Open flag] = 'Y'
                AND WR3.[Clock no] = EMP.[Clock no]
                AND WR3.Dated = 
                (
                SELECT  max(Dated)
                FROM    [Work records] WR4
                WHERE   WR4.[Open flag] = 'Y'
                        AND WR4.[Clock no] = EMP.[Clock no]
                        AND WR4.Dated <= '2013-01-07'
                )
        )
WHERE EMP.[Clocked in flag] = 'Y'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top