mySQL case函数

语法

CASE 字段名 WHEN 条件1 THEN 结果1

                  WHEN 条件2 THEN 结果2

                  ...

                  [ ELSE 结果N ]

                  END

条件可以是一个数值或公式。ELSE子句不是必须的。

还有一种写法:

   CASE   WHEN 字段名A = 数值 THEN 结果1

              WHEN 字段名A = 数值 THEN 结果2

              [ELSE 结果N]

              END

两种写法,可以实现相同的功能。具体使用哪种写法需根据实际情况做选择。

注意:case函数只返回第一个符合条件的值,剩下的case部分会被忽略。

例如,下图的代码,我们无法得到“第二类”这个结果

case when col_1 in ('a','b') then '第一类'
     when col_1 in ('a') then '第二类'
     else '其他' end  

使用case函数做统计

如下图所示

select
	COUNT(*) as clearingNum,
	SUM(case clearing_status when 0 then 1 else 0 end)  as newNum,
	SUM(case clearing_status when 1 then 1 else 0 end) as reconciledNum,
	SUM(case clearing_status when 2 then 1 else 0 end) as settledNum,
	SUM(case clearing_status when -1 then 1 else 0 end) as invalidNum
from fm_clearing

猜你喜欢

转载自blog.csdn.net/yx1166/article/details/80350629
今日推荐