简体   繁体   中英

calculating time between many dated in the same column with group by using MYSQL

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 :)

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:

在此处输入图片说明

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

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))

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM