1

我想在查询中加入两个表,从每个表中提取一些信息,但第二个表需要 TOP 1:

这得到了我的人员名单

SELECT [Clock no], [Card id], [Current pay cat], [Pay category] 
FROM Employees EMP 
WHERE [Clocked in flag] = 'Y'

现在对于该表中的每个人,我想加入这个查询:

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

到目前为止我所拥有的是这样的,但我似乎无法在添加 ORDER By 子句后立即使其工作:

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'
4

1 回答 1

2

子查询返回一行,不一定是 right Clock no。只看右边Clock no需要子查询和外部表之间的关系。那是不允许的join

一种解决方法是on条件中的子查询,例如:

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'
于 2013-01-07T12:56:31.177 回答