Reputation: 125
i have a data set which has the number id of customers and the dates of thier orders what i need to do is to calculate the number of days bewtween every order for each customer for example :
so i need to know the number of days between every order made for every customer . thanks for the help :)
Upvotes: 0
Views: 833
Reputation: 1269513
Use a simple window function!
select t.*,
datediff(order_date, lag(order_date) over (partition by id)) as diff
from t;
In SQL Server, this would be:
select t.*,
datediff(day, lag(order_date) over (partition by id), order_date) as diff
from t;
Upvotes: 0
Reputation: 13006
here's how you will do this, you can use dense_rank()
MySQL 8.0
select t1.id, t1.order_date
, ifnull(
datediff(cast(t1.order_date as datetime), cast(t2.order_date as datetime))
,0) as intrval
from (
select dense_rank() over (partition by id order by cast(order_date as datetime) asc) as rnk
, order_date, id
from table1) as t1
left join
(
select dense_rank() over (partition by id order by cast(order_date as datetime) asc) as rnk
, order_date, id
from table1) as t2
on t1.id = t2.id and t2.rnk+1 = t1.rnk
Output:
Upvotes: 1
Reputation: 1059
SQL without the window functions:
select t1.id as ID, datediff(dd, convert(datetime, t1.order_date), convert(datetime, t2.order_date)) as DaysBetweenOrders
from orders t1
inner join orders t2 on t1.id = t2.id
where convert(datetime, t2.order_date) =
(select min(convert(datetime, t3.order_date))
from orders t3 where t3.id = t1.id
and convert(datetime, t3.order_date) > convert(datetime, t1.order_date))
Upvotes: 0
Reputation: 3833
You may try this.
declare @tb table ( id int, order_date datetime)
insert into @tb ( id , order_date )
values ( 1, '2019-08-01' )
, ( 1, '2019-08-04' )
, ( 1, '2019-08-15' )
, ( 2, '2019-08-02' )
, ( 2, '2019-08-16' )
; with cte as (
select row_number() over (partition by id order by order_date) as Slno, Id, order_date from @tb)
select t.id, t.order_date , isnull( datediff(day, t1.order_date, t.order_date),0) as Diff
from cte as t left outer join cte as t1 on t.id=t1.id and t.slno=t1.slno+1
Upvotes: 0