SQL用排序函数取最大发货号行后如何关联Order_det表获取单价
实现方案
你可以在筛选出每个订单最大发货号的结果之后再关联Order_det表,这样只需要对最终的少量结果做关联操作,执行效率更高,修改后的完整SQL如下:
select with_max.Ord_num, with_max.Shipment_num, with_max.Item_code, with_max.Qty_to_pick, with_max.Qty_picked, t2.Unit_sales_price, t2.Unit_sales_price * with_max.Qty_picked as Total_price from ( select t1.*, max(shipment_num) over (partition by ord_num) as orders_max_ship_num from pick_det t1 ) with_max -- 此处关联Order_det表,关联条件为订单号+商品编码双匹配 left join Order_det t2 on with_max.Ord_num = t2.Ord_num and with_max.item_code = t2.item_code where with_max.shipment_num = with_max.orders_max_ship_num order by with_max.ord_num, with_max.item_code;
补充说明
如果你的业务场景能保证Order_det里一定存在对应Ord_num和item_code的记录,也可以把left join换成inner join,结果完全一致。
当然你也可以选择在子查询里先关联Order_det再做最大发货号筛选,不过这种方式需要先对全量Pick_det表做关联,数据量更大的情况下效率会低于先筛选后关联的写法。
内容的提问来源于stack exchange,提问作者Striker
相关产品推荐
相关产品推荐

