刚刚同时跑来问我一个sql语句顿时,一看我有点蒙,因为之前没有用过,所以在这里写下学习笔记加深印象。
语法如下:
CASE value WHEN [compare-value01] THEN result01 [WHEN [compare-value02] THEN result01 ...] [ELSE result] END
此sql语句我认为有点像条件语句。
意思是:
条件一,当字段value的值等于"compare-value"时,赋值为result01;
条件二,当字段value的值等于"compare-value"时,赋值为result02;
...
条件N,,赋值为result02;
结束
这么说肯定感觉很抽象,上实例,一看就明白了。
usersa表及数据如下图
样例1查询SQL
select *,
(CASE username WHEN "李四" THEN "四"
WHEN "张三" THEN "三"
ELSE 'more' END
)as "Column"
FROM usersa;
查询结果图
样例2查询SQL
select
sex,
count(case username when "李四" then "李四" end) as "李四",
count(case username when "张三" then "张三" end) as "张三"
from usersa
group by sex;
查询结果图
【参考资料】
http://www.jb51.net/article/28222.htm
来源:oschina
链接:https://my.oschina.net/u/225084/blog/213454