I want to write a query that uses 'joins concepts' to return, for each order, the number of days that passed since the same customer's previous order.
I am using the AdventureWorks2017
database, table Sales.SalesOrderHeader
I tried the following code, but i actually want it through joins concept:
select customerid,
orderdate,
salesorderid,
datediff(day,
(select top(1) s1.orderdate
from sales.SalesOrderHeader s1
where s1.CustomerID=s.CustomerID
and (s1.OrderDate = s.Orderdate
and s1.SalesOrderID < s.Salesorderid
or s1.OrderDate < s.orderdate)
order by s1.orderdate desc,s1.SalesOrderID desc
),
orderdate) as Daysdifference
from sales.SalesOrderHeader s
order by CustomerID,OrderDate,SalesOrderID
Starting from your existing query, a simple approach uses a lateral join:
This answers your question as of how to implement the logic with a join. Let me pinpoint, however, that this would be more efficiently expressed with
lag()
: