我想在查询中加入两个表,从每个表中提取一些信息,但第二个表需要 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'