0
votes

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?

1
SQL Server 2005? The time to upgrade was many, many years ago. You should be using a supported version. - Gordon Linoff
The query language is a proprietary one, thats based on server 2005. - InvalidSyntax
If the customer doesnt have an abandoned order do you still want to see him in the output? - zip
@zip nope, only customers with abandoned orders. - InvalidSyntax

1 Answers

0
votes

Here is what I have: Had to put it in a temp table because , sql 2005 doesnt support cte.

    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 into #AllAbandoned
    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)  
-- Here we only want the abandoned
        AND order_status != 'completed'

-- Here we say, get the one that is the most recent

Select * from #AllAbandoned a where not exists(Select 1 From #AllAbandoned b where a.Id = b.Id and a.OrderDate < b.OrderDate)