I wrote this query to show me the last purchase of each customers using "EXISTS" but it is not working. it returns all of the rows without filtering them. Can you please advise me how to resolve this issue?
Thank you in advance
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
);
2
Answers
It appears that you should be joining to that exists subquery:
But note that on any recent version of SQL Server, or on MySQL 8+, we can also use
ROW_NUMBER()
here:In your main query you select orders. In your subquery you look for orders matching the main order’s customer ID. This gives you at least one row (because you’ll find at least the same row again). You then aggregate these rows and group them by customer ID, thus getting exactly one row. So the question whether there
EXISTS
a row in your subquery is always answeredTRUE
.Here are three approaches. It seems you had something like the first or second in mind:
Get all orders where exists a match in the set of most recent orders:
This is a bit hard to read. It’s easier with
IN
:The same with an IN clause
You can also use
NOT EXISTS
:The most recent order is an order for with not exists a more recent order