mysql - 如何找到下一个订单ID mysql

标签 mysql sql

示例输入

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

最佳答案

你可以使用 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

关于mysql - 如何找到下一个订单ID mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50336423/

相关文章:

mysql - 如何从现有余额中获取新的运行余额?

python - 更新 tondb 连接时区而不生成新连接

javascript - CKEditor 无法显示我国的特殊字符 Æ Ø Å

sql - 查找员工用户有权访问的最快方法是什么?

php - 如何从其表格中恢复广告服务器的印象和点击

sql - 在 where 子句中使用 "If"条件

php - mysql json_object 结果上的 json_decode 不起作用

php - 将多个值传递到复选框的 'value' 属性

sql - 在sqlite多对多示例中,如何获取2个标签共有的书签?

sql - 需要数据存储建议 : Best way to store location + time data?