示例输入
order_id Customer_id Order_date
1 1 2017-11-01
2 2 2017-11-02
3 1 2017-11-03
4 2 2017-11-04
期望输出
order_id next_order_id
1 3
2 4
3
4
答案 0 :(得分:2)
您可以使用LEAD
:
SELECT order_id,
LEAD(order_id) OVER(PARTITION BY Customer_id ORDER BY Order_date) AS next_order
FROM tab
ORDER BY order_id;
<强> DBFiddle Demo - MySQL 8.0 强>
对于之前的MySQL版本:
SELECT order_id,
(SELECT order_id
FROM tab t2
WHERE t1.customer_id = t2.customer_id
and t2.Order_date > t1.order_date
ORDER BY Order_date LIMIT 1 ) AS next_order
FROM tab t1
ORDER BY order_id;
<强> DBFiddle Demo2 强>
答案 1 :(得分:0)
您还可以subquery
:
SELECT order_id,
(select order_id
from table
where Customer_id = t.Customer_id and
Order_date > t.Order_date
order by Order_date
LIMIT 1) as next_order_id
FROM table t
ORDER BY order_id;
答案 2 :(得分:0)
MySQL中的规范方式是相关的子查询:
select t.*,
(select t2.order_id
from t t2
where t2.customer_id = t.customer_id and t2.order_date > t.order_date
order by t2.order_date desc
limit 1
) as next_order_id
from t;
如果您使用的是MySQL 8.0,那么lead()
是更好的选择。