Mysql之case语句(附带实例)

Posted dreamfly_cc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql之case语句(附带实例)相关的知识,希望对你有一定的参考价值。

这段时间,做项目做累了,好不容易有点个人的学习时间,利用这个小时,总结一下,最近做统计的时候常用的case语句吧。

结构:case  when… then …end

1.判断的同时改变其值

eg:

                    select OperatorAccount,

                            case

                                         when CreateTime>‘2016-02-14 16:24:42‘ then ‘after‘

                                         when CreateTime<‘2016-02-14 16:24:42‘ then ‘before‘

                                         else ‘now‘ end stage

                    from log_login order by CreateTime DESC

技术分享

 

第二种写法

                    SELECT CallerNumber, CASE IsLocal

                                         WHEN 0 THEN ‘外线‘

                                         WHEN 1 THEN ‘内线‘ END

                    FROM cdr

技术分享


 

2.拆分一行为多列

eg:

                    SELECT SipAccount, COUNT(1) AS number,IsCheck
                    FROM cdr
                    GROUP BY SipAccount,IsCheck
技术分享

针对这个统计结果进行拆分(0表示未打分,1代表优秀,2代表合格,3代表不合格)

最终结果如下:

技术分享

 

所以最终要用到行拆分成三列,语句如下

                    SELECT SipAccount,
                    (CASE IsCheck WHEN 1 THEN number END) youxiu,
                    (CASE IsCheck WHEN 2 THEN number END) hege,
                    (CASE IsCheck WHEN 3 THEN number END) buhege
                    FROM
                    (SELECT SipAccount, COUNT(1) AS number,IsCheck
                    FROM cdr
                    GROUP BY SipAccount,IsCheck) AS a
技术分享

现在结果是这样的,你会发现虽然拆成了三列,但是最终结果还不是自己需要的,接下来就需要根据sipaccount来分组的同时对结果进行处理了。语句如下:

                    SELECT sipaccount,
                                         IF(MAX(youxiu) IS NULL,0, MAX(youxiu)) youxiu,
                                         IF(MAX(hege) IS NULL,0, MAX(hege)) hege,
                                         IF(MAX(buhege) IS NULL,0, MAX(buhege)) buhege
                    FROM
                    (SELECT SipAccount,
                                         (CASE IsCheck WHEN 1 THEN number END) youxiu,
                                         (CASE IsCheck WHEN 2 THEN number END) hege,
                                         (CASE IsCheck WHEN 3 THEN number END) buhege
                    FROM
  (SELECT SipAccount, COUNT(1) AS number,IsCheck  FROM cdr  GROUP BY SipAccount,IsCheck) AS a) AS b
                    GROUP BY sipaccount
技术分享

 最终得到了这个结果。正式我们需要的格式

 

 

以上是关于Mysql之case语句(附带实例)的主要内容,如果未能解决你的问题,请参考以下文章

Shell编程之条件语句——if语句case语句

Linux之Shell编程(10)--Shell流程控制语句实例演示

MySQL基础--08---流程控制( IF CASE) 和 游标

shellLinux shell 之 case 详解

MySQL 存储过程CASE语句用法

shell编程之函数和case多条件分支语句