【发布时间】:2014-09-22 14:53:46
【问题描述】:
oracle 中的人如何在 10 行中找到三列中最大的一个?
要求是我有三个日期列,我需要在 10 行中找到三列中的最大值。我知道最棒的会在一排中找到。
怎么做?
【问题讨论】:
-
所以你想要所有 30 个值中的最大值?或者您想要每列的最大值(总共三个值)?
oracle 中的人如何在 10 行中找到三列中最大的一个?
要求是我有三个日期列,我需要在 10 行中找到三列中的最大值。我知道最棒的会在一排中找到。
怎么做?
【问题讨论】:
怎么样
select max(greatest(date1, date2, date3, date4)) from my_table;
【讨论】:
greatest 函数评估的结果返回 null 是设计使然 asktom.oracle.com/pls/asktom/…,在您的情况下,克服这一点可能有些棘手。为避免使用 nvl,请参阅此 stackoverflow 问题的答案,这与您面临的问题非常相似:stackoverflow.com/questions/19186283/…
您可以在您的order by 中再次使用greatest
select * from (
select greatest(c1,c2,c3,c4) from mytable
order by greatest(c1,c2,c3,c4) desc
) t1 where rownum = 1
【讨论】:
With data as(
Select col1 dt from table union all
Select col2 from table union all
Select col3 from table union all
Select col4 from table
)
Select max(dt) max_dt
from data
/
假设 4 列是 DATE 数据类型。
它只使用MAX,而不是GREATEST。
更新:扩展@Thorsten 在下面的评论中提到的一个好点
GREATEST() 函数的问题在于,当您需要处理传递给它的 NULL 值时,您必须使用 NVL 来获得正确的输出。关于这个主题有很多问题,比如“如何使用 GREATEST 函数避免 NULL 值”等。
注意:从性能的角度来看,请在将此类逻辑应用到生产环境之前对其进行测试。
【讨论】:
这里有两种方法可以规避 GREATEST 的 NULL 问题(即 GREATEST 不仅在所有值都为 NULL 时返回 NULL,而且在至少一个值为 null 时已经返回 NULL 的问题,这使得使用 GREATEST 通常很麻烦)。
对于 n 列,您可以使用 n 个 COALESCE 表达式。每个表达式必须包含所有列,每列都以不同的列开头。
select
max(
greatest(
coalesce(col1,col2,col3,col4),
coalesce(col2,col3,col4,col1),
coalesce(col3,col4,col1,col2),
coalesce(col4,col1,col2,col3)
)
)
from mytable;
另一种方法是根本不使用 GREATEST,而是与 CASE 和 COALESCE 进行比较。每个值都与所有其他值进行比较。 col1 >= coalesce(col2,col1) 确保 col1 被视为大于或等于表达式,当 col2 为 NULL 时,只要 col1 本身不为 NULL。在 CASE 中,所有列都是 NULL,CASE 表达式默认为 NULL。 (可以添加else NULL 以使没有经验的读者可以看到。)
select
max(
case
when col1 >= coalesce(col2,col1) and col1 >= coalesce(col3,col1) and col1 >= coalesce(col4,col1) then col1
when col2 >= coalesce(col1,col2) and col1 >= coalesce(col3,col2) and col1 >= coalesce(col4,col2) then col2
when col3 >= coalesce(col1,col3) and col1 >= coalesce(col2,col3) and col1 >= coalesce(col4,col3) then col3
when col4 >= coalesce(col1,col4) and col1 >= coalesce(col2,col4) and col1 >= coalesce(col3,col4) then col4
end
)
from mytable;
【讨论】: