简体   繁体   English

Oracle SQL:在 WHERE 子句中的最大 function

[英]Oracle SQL: MAX function in WHERE clause

I've always received very helpful tips from this site and I'm very grateful for all of those so once again I'll try my luck!我一直从这个网站收到非常有用的提示,我非常感谢所有这些,所以我会再试一次运气!

I'm trying to use max function in where clause in order to fetch the latest revision of change order.我正在尝试在 where 子句中使用 max function 以获取变更单的最新版本。 So in table I have fields order_no, line_no, chg_order_no (revision number) and amount.所以在表中我有字段 order_no、line_no、chg_order_no(修订号)和数量。 So whenever user modifies purchase order then the system creates new change order and order_no and line_no will remain same but chg_order_no and amount changes.因此,每当用户修改采购订单时,系统就会创建新的变更单,order_no 和 line_no 将保持不变,但 chg_order_no 和金额会发生变化。 Note that chg_order_no can be anything from 1 to eg 100请注意,chg_order_no 可以是从 1 到例如 100 的任何值

order_no订单号 line_no line_no chg_order_no chg_order_no amount数量
order1订单1 1 1 1 1 100 100
order2订单2 1 1 1 1 250 250
order1订单1 1 1 2 2 300 300

Now I only want to fetch following rows:现在我只想获取以下行:

order_no订单号 line_no line_no chg_order_no chg_order_no amount数量
order2订单2 1 1 1 1 250 250
order1订单1 1 1 2 2 300 300

I have tried to use following select query but it doesn't seem to work for all orders我尝试使用以下 select 查询,但它似乎不适用于所有订单

SELECT co.order_no, co.chg_order_no,co.line_no, co.amount 
FROM CHANGE_ORDER co 
WHERE co.chg_order_no = (select MAX(chg_order_no) from CHANGE_ORDER)

Thanks in advance提前致谢

You can use this method, but you need a correlated subquery:你可以使用这个方法,但是你需要一个相关的子查询:

SELECT co.order_no, co.chg_order_no,co.line_no, co.amount 
FROM CHANGE_ORDER co 
WHERE co.chg_order_no = (select MAX(co2.chg_order_no)
                         from CHANGE_ORDER co2
                         where co.order_no = co2.order_no
                        );

Your version returns the maximum chg_order_no over all the data.您的版本返回所有数据的最大chg_order_no However, you only want it for each order_no .但是,您只希望每个order_no都使用它。

There are many ways to accomplish this.有很多方法可以做到这一点。 But Oracle has new functionality that lets you avoid a subquery:但是 Oracle 具有新功能,可让您避免子查询:

select co.*
from change_order co
order by row_number() over (partition by order_no order by chg_order_no desc)
fetch first 1 row with ties;

Add just this where clause in the subquery: where order_no = co.order_no在子查询中添加这个 where 子句: where order_no = co.order_no

SELECT co.order_no, co.chg_order_no,co.line_no, co.amount 
FROM CHANGE_ORDER co 
WHERE co.chg_order_no = (select MAX(chg_order_no) from CHANGE_ORDER where order_no = co.order_no)
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM