场景:假如你在网上买了一台空调,生成一个订单号xxxxxxx,该订单号有两个物料(空调内机和空调外机),在快递员送货时,我们只看该订单最终完成时间,也就是说,假如先送的空调内机,时间为2022-08-23 15:54:30,空调外机送达时间为2022-08-24 10:30:07,我们要的时间就是2022-08-24 10:30:07
解决方案:同一个订单按照时间降序排序,我们取第一条
知识点:row_number() over (partition by)
问题:订单并非像我举例中的有两条,有的订单可能有十几条
代码:
- select * from (
- select
- order_no,
- sh_time1,
- sh_time2,
- ROW_NUMBER() OVER (PARTITION BY order_no ORDER BY sh_time1,sh_time2 DESC NULLS LAST) rn
- from TABLE1 ) tb_oms
- where rn = 1
如果想取最早的一条记录,升序排列,取第一条即可
- select * from (
- select
- order_no,
- sh_time1,
- sh_time2,
- ROW_NUMBER() OVER (PARTITION BY order_no ORDER BY sh_time1,sh_time2 NULLS LAST) rn
- from TABLE1 ) tb_oms
- where rn = 1