|
DECODE函数:
基本语法为:DECODE(value, if1, then1, if2, then2, if3, then3,...ifn, thenn, else)
表示如果value等于if1时,DECODE函数的结果返回then1,...,如果不等于任何一个if值,则返回else。亦即:decode(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
用法示例:
select decode(sign(arg1-arg2),-1, arg1, arg2) from dual;
select decode(sign(3-5),1 ,3, 5) from dual ;
注:sign()函数根据某个值是0、正数还是负数,分别返回0、1、-1
CASE WHEN:
基本语法:
SELECT <myColumnSpec> =
CASE WHEN <A> THEN <somethingA>
WHEN <B> THEN <somethingB>
ELSE <somethingE> END
除了可以在select 中使用CASE 外,where 子句,group by 子句,order by 子句都可以使用
用法示例:
SELECT CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END AS "Range",
Title
FROM titles
where
CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives' END in('Average','Bargain')
GROUP BY CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives' END,
Title
ORDER BY CASE
WHEN price IS NULL THEN 'Unpriced'
WHEN price < 10 THEN 'Bargain'
WHEN price BETWEEN 10 and 20 THEN 'Average'
ELSE 'Gift to impress relatives'
END,Title
DECODE 与CASE WHEN 的比较
1、DECODE Oracle 特有;
2、CASE WHEN Oracle , SQL Server, MySQL 都可用;
3、DECODE 只能用做相等判断,但是可以配合sign函数进行大于,小于,等于的判断,CASE 可用于=,>=,<,<=,<>,is null,is not null 等的判断;
4、DECODE 使用其来比较简洁,CASE 虽然复杂但更为灵活;
|
|