zoukankan      html  css  js  c++  java
  • 【SQL】CASE与DECODE

    1. case..when case..when语句用于按照条件返回查询结果,如当我们想把emp表的工资按照多少分成几个不同的级别,并分别统计各个级别的员工数。SQL语句如下:
    select (case
             when sal <= 1000 then
              '1'
             when sal > 1000 and sal <= 2000 then
              '2'
             when sal > 2000 and sal <= 3000 then
              '3'
             when sal > 3000 and sal <= 4000 then
              '4'
             else
              '5'
           end) as Levels,
           count(*)
      from emp
     group by (case
                when sal <= 1000 then
                 '1'
                when sal > 1000 and sal <= 2000 then
                 '2'
                when sal > 2000 and sal <= 3000 then
                 '3'
                when sal > 3000 and sal <= 4000 then
                 '4'
                else
                 '5'
              end) order by levels;
    其中,when后可直接跟确定的条件,也可以像上面一样跟表达式。当我们想要使用group..by分组时,要把case..when整个语句放在group by 子句中,不能使用如上面case..when语句的别名"Levels"。


    2. decode函数
    (1)decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,缺省值)
    当条件等于值1,则返回值2;当条件等于值2,则返回值2...
    (2)decode(字段或字段的运算,值1,值2,值3)

    当字段或字段的运算等于值1,则返回值2,否则返回值3。

    如:有表如下


    我们想得到如下的查询结果:


    SQL语句如下:

    select country,decode(sex,'1','男','2','女') as sex,population from test;

  • 相关阅读:
    python列表--查找集合中重复元素的个数
    python3-打印一个进度条
    python3-sys模块
    python3-字符串操作
    python3-深浅复制
    python3-os模块
    接口和抽象类有什么区别
    集合知识
    面向对象的特征有哪些方面
    javadoc时候乱码-编码 GBK 的不可映射字符
  • 原文地址:https://www.cnblogs.com/NextAction/p/7366621.html
Copyright © 2011-2022 走看看