oracle 基于 rownum 条件的 Sql Max() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2906900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 20:42:01  来源:igfitidea点击:

Sql Max() function on an rownum condition

sqloracle

提问by toddlermenot

I saw something like the following in our production code:

我在我们的生产代码中看到了如下内容:

select max(col_val) from table_name where 
--set of conditions here
--AND
rownum=1;

This looked strange to me. Would the above code execute with the intended purpose?(selecting a max value from a set of values). Won't this select always return a single record from which the col_val would be chosen?. Thanks.

这对我来说看起来很奇怪。上面的代码会按预期目的执行吗?(从一组值中选择一个最大值)。这个选择不会总是返回从中选择 col_val 的单个记录吗?。谢谢。

回答by Shannon Severance

No. It is guarenteed to get the max of a set of values. It will return the first value only, where first value is driven by execution plan. Depending on the plan, the first value may be the max value also, but this could change because plans are not constant.

不。保证获得一组值的最大值。它将仅返回第一个值,其中第一个值由执行计划驱动。根据计划,第一个值也可能是最大值,但这可能会发生变化,因为计划不是恒定的。

SQL> create table t (i number);

Table created.

SQL> insert into t values (1);

1 row created.

SQL> insert into t values (2);

1 row created.

SQL> select i from t;

     I
----------
     1
     2

SQL> select max(i) from t;

    MAX(I)
----------
     2

SQL> select max(i) from t where rownum = 1;

    MAX(I)
----------
     1

SQL> 

回答by Andrey

it will take the first row that satisfies conditions. max seems to be excess here.

它将取满足条件的第一行。max 在这里似乎是多余的。