Oracle 取多列中最大值 greatest、最小值详解 least

1 概述

最值
greatest(c1, c2, cN):N 列中的 最大值
坑:若某列为空,则结果为空
least(c1, c2, cN) :N 列中的 最小值

2 示例

-- 类型    比较大小的依据
-- 数值      数值大小
-- 字符串    ascii大小  select ascii('a') from dual;
-- 时间      时间大小
-- NULL、'' 只要有 null,都是 null
select greatest(1, 2, 3) max_number,
       least(1, 2, 3) min_number,
       
       greatest('a', 'b', 'c') max_string,
       least('a', 'b', 'c') min_string,
       
       greatest(sysdate, sysdate + 1, sysdate + 2) max_date,
       least(sysdate, sysdate + 1, sysdate + 2) min_date, 
       
       greatest(1, null, 2) max_null,
       least(1, '', 2) min_null
  from dual;

3 扩展

3.1 获取非空列值

/*
-- 依据:进行判空操作 或 给默认值
select nvl('', '空') a,
       nvl2('', '非空', '空') b,
       -- 获取第一个非空的值
       coalesce('', '', '', '非空') c -- N 列
  from dual;
*/
with t_temp as (
  select '' col1, 'a' col2, 'b' col3 from dual
)
select greatest(coalesce(tt.col1, tt.col2, tt.col3),
                coalesce(tt.col2, tt.col3, tt.col1),
                coalesce(tt.col3, tt.col1, tt.col2)) 最大值
 from t_temp tt;

3.2 隐式类型转换

  • 结论:表达式的数据类型以 第一个 exp 为准
create or replace view scott.test_date_type as
    select greatest(1, '2') string_to_number, -- number
           least('1', 2) number_to_string -- varchar2
      from dual
;

select t.column_name,
       t.data_type
  from all_tab_columns t
 where t.table_name = upper('test_date_type');

输出结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鱼丸丶粗面

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值