Home > OS >  SQL Query to get value of recent order alongwith data from other tables
SQL Query to get value of recent order alongwith data from other tables

Time:09-16

I am writing an SQL query to get data from more than 3 tables, but for simplifying the question here I am using a similar scenario with 3 tables.

Table1 Customer (PK-CustomerID, Name)

CustomerID Name
1 John
2 Tina
3 Sam

Table2 Sales (FK-Id, SalePrice)

ID SalePrice
1 200.00
2 300.00
3 400.00

Table3 Order (PK-Id, FK-CustomerID, Date, Amount)

Id CustomerID Date Amount
101 1 25-09-2021 30.0
102 1 27-09-2021 40.0
103 2 19-09-2021 60.0

In the output, Date and Amount should be the from most recent Order (latest Date), for a customer

My approach was

    Select c.CustomerID, c.Name, s.SalePrice, RecentOrder.Date, RecentOrder.Amount from 
    Customer as c
    LEFT JOIN Sales s ON c.CustomerID = s.ID
    LEFT JOIN (SELECT top 1 o.Date, o.Amount, o.CustomerID  
    FROM Order o, Customer c1 WHERE c1.CustomerID = o.CustomerID ORDER BY o.Date DESC) 
    RecentOrder ON c.CustomerID = RecentOrder.CustomerID

Output I get

CustomerID, Name, SalePrice, Date, Amount

CustomerID Name SalePrice Date Amount
1 John 200.00 27-09-2021 40.0
2 Tina 300.00 null null
3 Sam 400.00 null null

The output I get includes the most recent order out of all the orders. But I want to get the recent order out of the orders made by that customer

Output Required

CustomerID, Name, SalePrice, Date, Amount

CustomerID Name SalePrice Date Amount
1 John 200.00 27-09-2021 40.0
2 Tina 300.00 19-09-2021 60.0
3 Sam 400.00 null null

CodePudding user response:

You need to pre-aggregate or identify the most recent order for each customer order, your query is selecting 1 row for all orders.

Try the following (untested!)

select c.CustomerID, c.Name, s.SalePrice, o.Date, o.Amount 
from Customer c
left join Sales s on c.CustomerID = s.ID
outer apply (
    select top (1) date, amount
    from [order] o
    where o.CustomerId=c.CustomerId
    order by Id desc
)o

CodePudding user response:

Instead of subquery in left join, you can check with outer apply.

Check following way

Select c.CustomerID, c.Name, s.SalePrice, RecentOrder.Date, RecentOrder.Amount 
from Customer c
LEFT JOIN Sales s ON c.CustomerID = s.ID
OUTER APPLY (
SELECT top 1 o.Date, o.Amount, o.CustomerID  
FROM [Order] o 
WHERE o.CustomerID = c.CustomerID ORDER BY o.Date DESC) RecentOrder`   
  • Related