计算MySQL中每个唯一ID的前一行的日期差异

时间:2017-08-18 18:00:36

标签: mysql

我是一名SQL初学者,正在学习查询的绳索。我正在尝试找到同一客户购买之间的日期差异。我有一个如下所示的数据集:

ID | Purchase_Date
==================
1  | 08/10/2017
------------------
1  | 08/11/2017
------------------
1  | 08/17/2017
------------------
2  | 08/09/2017
------------------
3  | 08/08/2017
------------------
3  | 08/10/2017

我希望有一个列显示每个独特客户购买的天数差异,以便输出如下所示:

ID | Purchase_Date | Difference
===============================
1  | 08/10/2017    | NULL
-------------------------------
1  | 08/11/2017    | 1
-------------------------------
1  | 08/17/2017    | 6
-------------------------------
2  | 08/09/2017    | NULL
-------------------------------
3  | 08/08/2017    | NULL
-------------------------------
3  | 08/10/2017    | 2

使用MySQL查询的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

这在MySQL中相当棘手。如果你是一个开始,可能最好的学习方法是相关的子查询方法:

select t.*, datediff(purchase_date, prev_purchase_date) as diff
from (select t.*,
             (select t2.purchase_date
              from t t2
              where t2.id = t.id and
                    t2.purchase_date < t.purchase_date
              order by t2.purchase_date desc
              limit 1
             ) as prev_purchase_date
      from t
     ) t;

如果您有(id, purchase_date)的索引,那么效果应该没问题。

答案 1 :(得分:2)

不是那么难,只需使用子查询为客户的每个现有购买找到先前的购买,并自行加入该记录。

Select t.id, t.PurchaseDate, p.Purchase_date,
    DATEDIFF(t.PurchaseDate, p.Purchase_date) Difference
From myTable t          -- t for This purchase record
    left join myTable p -- p for Previous purchase record
       on p.id = t.Id 
         and p.purchase_date =
           (Select Max(purchase_date)
            from mytable
            where id = t.id
               and purchase_date < 
                   t.purchaseDate) 

答案 2 :(得分:1)

可以解决它不使用从属子查询

SELECT yt.id, create_date, NULLIF(yt.create_date - tm.min_create_date, 0)
FROM your_table yt
JOIN
(
  SELECT id, MIN(create_date) min_create_date
  FROM your_table
  GROUP BY id
) tm ON tm.id = yt.id

sqlfiddle demo