Home > Database > Mysql Tutorial > body text

Oracle CASE WHEN 用法介绍

WBOY
Release: 2016-06-07 16:49:52
Original
1419 people have browsed it

1. CASE WHEN 表达式有两种形式 --简单Case函数 CASE sex WHEN

1. CASE WHEN 表达式有两种形式

--简单Case函数 

CASE sex 
WHEN '1' THEN '男' 
WHEN '2' THEN '女' 
ELSE '其他' END 

--Case搜索函数 

CASE
WHEN sex = '1' THEN '男' 
WHEN sex = '2' THEN '女' 
ELSE '其他' END

2. CASE WHEN 在语句中不同位置的用法
 
2.1 SELECT CASE WHEN 用法

SELECT  grade, COUNT (CASE WHEN sex = 1 THEN 1      /*sex 1为男生,2位女生*/
                      ELSE NULL
                      END) 男生数,
                COUNT (CASE WHEN sex = 2 THEN 1
                      ELSE NULL
                      END) 女生数
    FROM students GROUP BY grade;

2.2 WHERE CASE WHEN 用法

SELECT T2.*, T1.*
  FROM T1, T2
  WHERE (CASE WHEN T2.COMPARE_TYPE = 'A' AND
                  T1.SOME_TYPE LIKE 'NOTHING%'
                THEN 1
              WHEN T2.COMPARE_TYPE != 'A' AND
                  T1.SOME_TYPE NOT LIKE 'NOTHING%'
                THEN 1
              ELSE 0
          END) = 1

2.3 GROUP BY CASE WHEN 用法

SELECT 
CASE WHEN salary WHEN salary > 500 AND salary WHEN salary > 600 AND salary WHEN salary > 800 AND salary ELSE NULL END salary_class, -- 别名命名
COUNT(*) 
FROM    Table_A 
GROUP BY 
CASE WHEN salary WHEN salary > 500 AND salary WHEN salary > 600 AND salary WHEN salary > 800 AND salary ELSE NULL END;

3.关于IF-THEN-ELSE的其他实现
 
3.1 DECODE() 函数

, , , , )
from  employees;

貌似只有Oracle提供该函数,而且不支持ANSI SQL,语法上也没CASE WHEN清晰,,个人不推荐使用。

3.2 在WHERE中特殊实现

T1.SOME_TYPE )
        T1.SOME_TYPE )

这种方法也是在特殊情况下使用,要多注意逻辑,不要弄错。

--------------------------------------------------------------------------------

Linux-6-64下安装Oracle 12C笔记

在CentOS 6.4下安装Oracle 11gR2(x64)

Oracle 11gR2 在VMWare虚拟机中安装步骤

Debian 下 安装 Oracle 11g XE R2

--------------------------------------------------------------------------------

本文永久更新链接地址:

linux

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!