zoukankan      html  css  js  c++  java
  • mysql if--else

    SQL之case when then用法

    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  
    复制代码

    这两种方式,可以实现相同的功能。简单case函数的写法相对比较简洁,但是和case搜索函数相比,功能方面会有些限制,比如写判定式。

    还有一个需要注重的问题,case函数只返回第一个符合条件的值,剩下的case部分将会被自动忽略。

    --比如说,下面这段sql,你永远无法得到“第二类”这个结果
    case when col_1 in ('a','b') then '第一类'
         when col_1 in ('a') then '第二类'
         else '其他' end  

    下面实例演示:

    3、将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
    复制代码
  • 相关阅读:
    Java类练习一则
    windows下安装Apache+PHP
    Java 数组/对象练习一则
    windows 安装 apache 报错解决
    延时任务机制
    Javashop电商系统-会员登录方式
    基于canvas商品海报生成源码分享
    uniapp引入微信小程序直播组件
    电商系统中库存的存储于扣减
    电商系统nuxt的中间件代码分享
  • 原文地址:https://www.cnblogs.com/nyfz/p/9111831.html
Copyright © 2011-2022 走看看