zoukankan      html  css  js  c++  java
  • MySQL 关于case when结合group by用时的写法举例

    原表是个员工档案,共583人,但case when结合group by用时,写法不同,其出来的结果也不同

    例1:

    select distinct a.Branch,
    case when kultur = '硕士' then sum(num) else '0' end as 研究生学历,
    case when kultur = '本科' then sum(num) else '0' end as 大本学历,
    case when kultur = '大专' then sum(num) else '0' end as 大专学历,
    case when kultur = '中专' then sum(num) else '0' end as 中专学历,
    case when kultur = '高中' or kultur ='职高' or kultur ='中职'  then sum(num) else '0' end as 高中学历,
    case when kultur = '初中' then sum(num) else '0' end as 初中学历,
    case when kultur = '小学' then sum(num) else '0' end as 小学学历,
    case when kultur = '' or kultur is null  then sum(num) else '0' end as 未填写学历
    from( select Branch,kultur,count(*) as num 
            from tb_Stuffbusic 
         group by branch,kultur) a
    Group by a.Branch,a.kultur

    结果如下图:

    例2:

    select Branch as 部门名称,count(branch) as 总人数,
    sum(case when kultur = '硕士' then 1 else '0' end) as 研究生学历,
    sum(case when kultur = '本科' then 1 else '0' end) as 大本学历,
    sum(case when kultur = '大专' then 1 else '0' end) as 大专学历,
    sum(case when kultur = '中专' then 1 else '0' end) as 中专学历,
    sum(case when kultur = '高中' or kultur ='职高' or kultur ='中职'  then 1 else '0' end) as 高中学历,
    sum(case when kultur = '初中' then 1 else '0' end) as 初中学历,
    sum(case when kultur = '小学' then 1 else '0' end) as 小学学历,
    sum(case when kultur = '' or kultur is null  then 1 else '0' end) as 未填写学历
    from tb_Stuffbusic         
    group by branch

    结果如下图:

    例3:表中ID字段有时字段值长不够4位,但不能超过4位,故通过下面语句一次性加上。
    UPDATE tb_Stuffbusic
    SET ID = CASE WHEN LEN(ID) = 1 THEN '000'+ID
                  WHEN LEN(ID) = 2 THEN '00'+ID
                  WHEN LEN(ID) = 3 THEN '0'+ID
                  ELSE ID
                  END

  • 相关阅读:
    C++ 数组array与vector的比较
    C/C++头文件区别
    C/C++ 标准输入输出重定向
    C文件读写
    输入输出重定向
    【剑指offer26 二叉搜索树与双向链表】
    【剑指offer25 复杂链表的复制】
    【剑指offer23 二叉搜索树的后序遍历序列】
    【剑指offer22 从上往下打印二叉树 & 60 把二叉树打印成多行】
    【剑指offer21 栈的压入、弹出序列】
  • 原文地址:https://www.cnblogs.com/lixiaozhi/p/9198552.html
Copyright © 2011-2022 走看看