zoukankan      html  css  js  c++  java
  • mysql case when函数

    case具有两种格式。简单case函数和case搜索函数。

    # --简单case函数
    case sex
      when '1' then ''
      when '2' then '女’
      else '其他' end
    # --case搜索函数 case when sex =
    '1' then '' when sex = '2' then '' else '其他' end
    SQL> select * from users;
     
     ID NAME                        SEX
    ------ -------------------- ----------
     1 张一                 
     2 张二                          1
     3 张三                 
     4 张四                 
     5 张五                          2
     6 张六                          1
     7 张七                          2
     8 张八                          1

    select u.id,u.name,
      2    (case u.sex
      3      when 1 then ''
      4      when 2 then ''
      5      else '空的'
      6      end
      7     )性别
      8  from users u;
    ID NAME 性别
    -------------------- ------ 1 张一 空的 2 张二 男 3 张三 空的 4 张四 空的 5 张五 女 6 张六 男 7 张七 女 8 张八 男

    将sum与case结合使用,可以实现分段统计。
    如果现在希望将上表中各种性别的人数进行统计,sql语句如下:

    SQL> select
      2    sum(case u.sex when 1 then 1 else 0 end)男性,
      3    sum(case u.sex when 2 then 1 else 0 end)女性,
      4    sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性别为空
      5  from users u;
     
            男性         女性       性别为空
    ---------- ---------- ----------
             3          2          0
    
    --------------------------------------------------------------------------------
    SQL> select
      2    count(case when u.sex=1 then 1 end)男性,
      3    count(case when u.sex=2 then 1 end)女,
      4    count(case when u.sex <>1 and u.sex<>2 then 1 end)性别为空
      5  from users u;
     
            男性          女       性别为空
    ---------- ---------- ----------
             3          2          0
  • 相关阅读:
    <大学祭>
    使用rest方式修改服务端xml文件
    tsql的奇特语法
    Dandelion
    正则中关于修饰符g以及exec和match区别的一个小demo
    如何将一个盒子在显示在浏览器的正中间
    Js中的this指向问题
    CSS通过边框border-style来写小三角
    用单例模式封装常用方法 utils class v1.0
    JS中检测数据类型的四种方法
  • 原文地址:https://www.cnblogs.com/mlllily/p/14139652.html
Copyright © 2011-2022 走看看