case when语法以及与group by的配合使用

一:case when语法:

case when有两种语法:

语法1:

case 某字段

when 值1 then 伪值1

when 值2 then 伪值2

......

else 伪值n

end

注意,when之间没有任何标点符号,且最后要以end结尾,否则会报语法错误。

如有一种常见情况是,数据库中保存性别的字段用的是整型,0代表男,1代表女,2代表未知,但是在查询的时候,想直接查出来,则可以用case when,在select后面跟case when,如下

select case Fgender when 0 then '男' when 1 then '女' else '未知' end from t_patient limit 10;

上面sql语句查出来的列名,会是【case Fgender when 0 then '男' when 1 then '女' else '未知' end】,可读性不高,所以最好用as重命名,如

select case Fgender when 0 then '男' when 1 then '女' else '未知' end as Fgender from t_patient limit 10;

这样,查出来的列名会是Fgender。

语法2:

case

when 条件1 then 伪值1

when 条件2 then 伪值2

......

else 伪值n

end

如上sql语句可改为

select case when Fgender = 0 then '男' when Fgender = 1 then '女' else '未知' end as Fgender from t_patient limit 10;

以上两种语法,else语句可以省略,在省略的情况下,如果有一些记录,不满足所有的when的情况,则这些记录查出来对应字段值会为null。

二、case when可以用在哪里

1、case when用在select后,如上述情况

2、case when用在group by后,用以实现分段统计功能。

比如想根据成绩表统计一下各分数段的人数,想要的结果如下

区间 人数
0-60 xx
60-90 xx
90-100 xx

那么sql语句可以写成

select
case
when score between 0 and 60 then '0-60'
when score between 60 and 90 then '60-90'
when score between 90 and 100 then '90-100'
end
as `区间`, count(1) as `人数`
from t_score
group by `区间`;

如此,查出来的结果是

区间 人数
60-90 6
90-100 1

3、如果想要的结果形如

0-60 60-90 90-100
0 6 3

这是一种典型的行列转换。行列转换也可用case when实现:

select
sum(case when score between 0 and 60 then 1 else 0 end) as `0-60`,
sum(case when score between 60 and 90 then 1 else 0 end) as `60-90`,
sum(case when score between 90 and 100 then 1 else 0 end) as `90-100`
from t_score;

查出来的结果是

0-60 60-90 90-100
0 6 3

END

posted on   koushr  阅读(6702)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示