[英]Calculate date difference from previous row of each unique ID in MySQL
I am a SQL beginner and am learning the ropes of querying. 我是一名SQL初学者,正在学习查询的绳索。 I'm trying to find the date difference between purchases by the same customer.
我正在尝试查找同一位客户购买之间的日期差异。 I have a dataset that looks like this:
我有一个看起来像这样的数据集:
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
I want to have a column that shows the difference in days for each unique customer purchase, so that the output will look like this: 我希望有一个列显示每个唯一客户购买的天数差异,以便输出看起来像这样:
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
What would be the best way to go about this using a MySQL query? 使用MySQL查询解决此问题的最佳方法是什么?
This is rather tricky in MySQL. 在MySQL中,这相当棘手。 Probably the best way to learn if you are a beginning is the correlated subquery method:
了解您是否是开始的最好方法是相关子查询方法:
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;
Performance should be okay if you have an index on (id, purchase_date)
. 如果您在
(id, purchase_date)
上有一个索引,则性能应该可以。
Not so hard, just use a subquery to find previous purchase for each existing purchase for the customer, and self-join to that record. 并不难,只需使用子查询为该客户的每个现有购买查找先前购买,然后自动加入该记录。
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)
It is possible to solve it not using dependent subquery 可以不使用依赖子查询来解决
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.