I have a Customers
table with CustomerID
and CustomerName
.
I then have a Orders
table with CustomerID
, datetime OrderPlaced
and datetime OrderDelivered
.
Bearing in mind that not all customers have placed orders, I would like to get a list of CustomerName
, OrderPlaced
and OrderDelivered
but only for customers that have placed orders and whose orders have already been delivered, and only the most recent OrderPlaced
per customer.
I started by doing (fully aware that this does not implement the OrderDelivered
limitation to it yet, but already not doing what I want):
SELECT CustomerID,
(SELECT TOP 1 OrderDelivered
FROM Orders ORDER BY OrderDelivered DESC) AS OrderDelivered
FROM Customer
WHERE OrderDelivered IS NOT NULL
But already MS SQL doesn't like this, it says that it doesn't know what OrderDelivered
is on the WHERE
clause.
How can I accomplish this?