Mysql之case語句(附帶執行個體)

來源:互聯網
上載者:User

標籤:

這段時間,做項目做累了,好不容易有點個人的學習時間,利用這個小時,總結一下,最近做統計的時候常用的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語句(附帶執行個體)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.