MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下产品。

那么其中mysql case语句怎么用?
mysql 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
|

最终得到了这个结果。正是我们需要的格式。
(责任编辑:yang) |