我想在查询中连接两个表,从每个表中提取一些信息,但第二个表需要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'
答案 0 :(得分:2)
子查询返回一行,不一定是右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'