首批通过分布式安全可靠测评,为关键业务系统打造
查询中使用 CASE 函数
更新时间:2026-06-25 14:24:00
CASE 表达式可以实现类似 IF...THEN...ELSE 的逻辑而不用调用子程序。CASE 表达式有两种使用方法,简单的和带搜索条件的。
示例
示例 1
在查询中使用简单的 CASE 表达式,将国家代码缩写翻译为全称。
创建
t_case表。obclient> CREATE TABLE t_case(id number NOT NULL PRIMARY KEY, abbr varchar(5)); Query OK, 0 rows affected在
t_case表中插入数据。obclient> INSERT INTO t_case VALUES (1,'US'),(2,'UK'),(3,'CN'),(4,'JP'); Query OK, 4 rows affected Records: 4 Duplicates: 0 Warnings: 0使用
CASE表达式查询国家代码对应的全称。obclient> SELECT id, abbr, CASE abbr WHEN 'US' THEN 'America' WHEN 'UK' THEN 'English' WHEN 'CN' THEN 'China' ELSE 'UNKOWN' END full_name FROM t_case ; +----+------+-----------+ | ID | ABBR | FULL_NAME | +----+------+-----------+ | 1 | US | America | | 2 | UK | English | | 3 | CN | China | | 4 | JP | UNKOWN | +----+------+-----------+ 4 rows in set
示例 2
在查询中使用带搜索条件的 CASE 表达式。
创建
t_case2表。obclient> CREATE TABLE t_case2(id number NOT NULL PRIMARY KEY, c_date date ); Query OK, 0 rows affected在
t_case2表中插入数据。obclient> INSERT INTO t_case2(id,c_date) VALUES (1,to_date('2019-03-01','yyyy-mm-dd')) ,(2,to_date('2019-05-08','yyyy-mm-dd')) ,(3,to_date('2019-07-07','yyyy-mm-dd')) ,(4,to_date('2019-10-11','yyyy-mm-dd')) ,(5,to_date('2019-12-12','yyyy-mm-dd')) ,(6,to_date('2020-01-05','yyyy-mm-dd')); Query OK, 6 rows affected Records: 6 Duplicates: 0 Warnings: 0使用带搜索条件的 CASE 表达式,查询
Duration列数据。obclient> SELECT id, c_date, CASE WHEN months_between(sysdate, c_date) > 12 THEN 'More than one year ago' WHEN months_between(sysdate, c_date) > 9 THEN 'More than three quarters ago' WHEN months_between(sysdate, c_date) > 6 THEN 'More than half a year ago' WHEN months_between(sysdate, c_date) > 3 THEN 'More than a quarter ago' WHEN months_between(sysdate, c_date) >= 0 THEN 'Within a quarter' ELSE 'Illegal' END "Duration" FROM t_case2; +----+-----------+------------------------+ | ID | C_DATE | Duration | +----+-----------+------------------------+ | 1 | 01-MAR-19 | More than one year ago | | 2 | 08-MAY-19 | More than one year ago | | 3 | 07-JUL-19 | More than one year ago | | 4 | 11-OCT-19 | More than one year ago | | 5 | 12-DEC-19 | More than one year ago | | 6 | 05-JAN-20 | More than one year ago | +----+-----------+------------------------+ 6 rows in set