I have three tables: Customer, Product, Orders
I am trying to identify all customers that have created an abandoned order (order_status != 'completed') but have no other orders that were completed (order_status != 'completed').
I have the following query which returns all the orders that meet this critera, but have multiple instances of the customer from various orders, I just need ONE instance of that customer and preferably the most recent order thats been abandoned.
SELECT
c.Id as Id,
c.Name as FullName,
o.Id as Order_Id,
o.OrderStatus,
o.OrderDate,
o.PaidByCC,
p.ProductStatus,
From Orders o
Join Customers c
On c.Id = o.CustomerId
Join Product p
On o.ProductId = p.[Product ID]
WHERE o.Type = 'Service'
AND o.PaidByCC = 0
AND o.OrderStatus IS NULL
AND p.State = 'available'
AND CONVERT(date, o.OrderDate) >= Convert(date, DATEADD(day, -30, GETDATE()))
AND NOT EXISTS (Select o1.Id
From Orders o1
Where o1.OrderStatus = 'Placed'
AND o.CustomerId = o1.CustomerId)
How can I do this?