我有客户的订单数据表,想要找出平均值。客户进行第二次交易所需的天数,在第一次交易之后,#天从第二次交易到第三次,依此类推。示例表:
User ID Rank Time
111 1 01/08/17
111 2 05/08/17
111 3 08/08/17
111 4 10/08/17
111 5 15/08/17
111 6 20/08/17
112 1 07/08/17
112 2 08/08/17
112 3 09/08/17
112 4 10/08/17
感谢advacne
答案 0 :(得分:0)
获取第一个日期,然后将每个日期与前一个日期进行比较:
set @d := (select date from yourTable where userid=111 and rank=1);
select rank, datediff( date, @d), @d:=date FROM yourTable;
你会得到这样的东西:
1 0 2017-08-01
2 4 2017-08-05
3 3 2017-08-08
4 3 2017-08-11
5 6 2017-08-17
然后只需在查询中添加一小部分内容:
set @d := (select date from yourTable where userid=111 and rank=1);
select avg(days) from
(select rank, datediff( date, @d) days, @d:=date FROM yourTable) td;
结果将是:
avg(days)
3.2000