SQL 使用CASE表示式求三列中的最大值

2021-09-19 05:28:44 字數 652 閱讀 2312

--求x、y和z三者中的最大值

select num,

case when case when x < y then y else x end < z

then z

else case when x < y then y else x end

end as greatest

from greatests;

如果是oracle和mysql資料庫,那麼我們可以使用下面的簡便方法求解。

select num, greatest(x,y,z) as greatest 

from greatests;

如果不止三列,存在4列、5列時,可以使用行轉列,再通過max函式求解。

select num, max(col) as greatest

from (select num, x as col from greatests

union all

select num, y as col from greatests

union all

select num, z as col from greatests) tmp

group by num;

SQL高階查詢 case表示式

case表示式可以在sql中實現if then else型的邏輯,oracle database 9i及以上版本支援case表示式,case工作方式與decode 類似 有兩種型別的case表示式 1.簡單case表示式,使用表示式確定返回值 case search expression when ...

SQL基礎 函式 謂詞 CASE表示式

numeric m,n 資料型別 m位數 包含小數字 n位小數字 sql sever select cast current timestamp as date as cur date oracle select current date from dual db2 select current d...

decode 和SQL語法case表示式

方法一 使用sql99標準通用語法中的case表示式,將職位是分析員的,工資 1000 職位是經理的,工資 800 職位是其它的,工資 400 select ename 姓名 job 職位 sal 原工資 case job when analyst then sal 1000 when manage...