这在MySQL上应该很简单,但我很困惑为什么SQL Server 2008会这样做是不可能的。
SELECT * FROM Customers AS cust
LEFT JOIN (SELECT TOP 1 * FROM Vehicles AS v WHERE v.CustNo=cust.CustNo) AS veh ON veh.CustNo=cust.CustNo;
错误是
The multi-part identifier "cust.CustNo" could not be bound.
任何想法的人?
答案 0 :(得分:1)
这是查询:
SELECT *
FROM Customers cust LEFT JOIN
(SELECT TOP 1 *
FROM Vehicles v
WHERE v.CustNo = cust.CustNo
) veh
ON veh.CustNo = cust.CustNo;
我不知道任何允许子查询中的关联子句的数据库。您可以使用OUTER APPLY
完成此操作:
SELECT *
FROM Customers cust OUTER APPLY
(SELECT TOP 1 *
FROM Vehicles v
WHERE v.CustNo = cust.CustNo
) veh;
答案 1 :(得分:0)
以下是使用row_number()
的一种方法:
select *
from (
SELECT *, row_number() over (partition by cust.custno order by v.custno) rn
FROM Customers cust
LEFT JOIN Vehicles v ON v.CustNo=cust.CustNo
) t
where rn = 1