我对此进行了很多思考并且花了很多时间,但无处可去。
我有一个如下表,我们称它为产品表。
customer_id product_id Type order_date completed_date
123 A1 X 11/07/2016 14/07/2016
456 A2 X 12/07/2016 15/07/2016
789 A3 X 13/07/2016 16/07/2016
123 A4 Y 15/07/2016 17/07/2016
456 A5 Y 16/07/2016 18/07/2016
789 A6 Y 17/07/2016 19/07/2016
目标是找出customer_id,其中订单类型Y的order_date是同一客户订单类型X的次日,即123是X订单在7月14日完成的客户,Y订单是放在下一个日期。
我试过给同一个表两个别名并加入它们,但我做错了,结果不正确。请帮忙。
最佳答案
select p.customer_id
from product_table p
join product_table p1 on p1.customer_id = p.customer_id and p1.type = 'Y' and p1.order_date = date_add(p.completed_date, interval 1 day)
where p.`type` = 'X'
结果
+-------------+
| customer_id |
+-------------+
| 123 |
| 456 |
| 789 |
+-------------+
3 rows in set (0.00 sec)
关于MYSQL - 在单个表中查找具有日期比较约束但具有唯一标识符的多行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40357777/