我编写此查询是为了显示每个客户使用“EXISTS”的最后一次购买,但它不起作用。它返回所有行而不过滤它们。您能告诉我如何解决这个问题吗? 先谢谢你了
SELECT O1.custid, O1.orderid, O1.orderdate, O1.empid
FROM Sales.Orders AS O1
WHERE EXISTS (
SELECT O2.custid, MAX(O2.orderdate)
FROM Sales.Orders AS O2
WHERE O2.custid=O1.custid
GROUP BY O2.custid
);
看来您应该加入到现有的子查询中:
SELECT O1.custid, O1.orderid, O1.orderdate, O1.empid
FROM Sales.Orders AS O1
INNER JOIN (
SELECT O2.custid, MAX(O2.orderdate) AS maxorderdate
FROM Sales.Orders AS O2
GROUP BY O2.custid
)
ON O2.custid = O1.custid AND
O2.maxorderdate = O1.orderdate;