case when then 与 count联合使用

本文介绍了如何在SQL中利用case when then与count函数结合,统计不同省份的男女数量。通过逐步解析查询语句,展示了如何从基础的查询男女总数,到按省份统计男女数量,最后聚焦特定省份进行计数。案例涵盖了多种使用场景,并提供了相关知识点补充。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们都知道SQL中适用case when then来转化数据库中的信息

      比如  select (case sex when 0 then '男' else '女' end) AS sex  from studentInfo

那么在集合函数中它有什么用呢 ?

 

假设数据库有一张表名为student的表。

如果现在要你根据这张表,查出江西省男女个数,广东省男生个数,浙江省男女个数 怎么写SQL语句?

答案是:

select sex ,

  count ( case province when '广东省' then '广东省' end )as 广东省 ,

  count ( case province when '江西省' then '江西省' end )as 江西省 ,

  count ( case province when '浙江省' then '浙江省' end )as 浙江省

  from student group by sex

count()函数即根据给定的范围和group by(统计方式) 而统计行数据的条数

我们一步步来理解上面语句

1.  select sex from student (查询数据表中的存在的男女条数)

2.select sex, count (*) as num from student group by sex  (查询表中男女数量)

3.select sex ,province, count (*)as num from student group by sex,province (查询各省男女数量)

  重点来了,如果我把count(*) 中的 *号换成任一列名呢? 如count(province) 会怎样?

4.select sex ,province, count (province)as num from student group by sex,province (查询各省男女数量)

  又有count (province)等价于 count(case province when '浙江省' then '浙江省' else province end )

  但是如果我们缩小范围呢即count(case province when '浙江省' then '浙江省' end ) 那么请看下面

5.select sex ,province, count ( case province when '浙江省' then '浙江省' end )as num from student group by sex,province

  即统计男女数量范围限定在浙江省 再精简一下即下面

6.select sex, count ( case province when '浙江省' then '浙江省' end ) as 浙江省 from student group by sex

  已经接近我们的要求了,现在只要加上另几个字段就是了

7.select sex ,count ( case province when '广东省' then '广东省' end )as 广东省 ,count ( case province when '江西省' then '江西省' end )as 江西省 ,count ( case province when '浙江省' then '浙江省' end )as 浙江省 from student group by sex

  小结:当然实现有很多种方法 可以多个子查询拼接起来也不无可厚非。我这只是一种思路

  补充:case when then 知识点

  (1) select (case province when '浙江省' then '浙江' when '江西省' then '江西' end  ) as 省份 from student

  如果默认范围如果没全包含则为空 

  (2)select (case province when '浙江省' then '浙江' when '江西省' then '江西' else province end  ) as 省份 from student

 

Eg:查找每个订单中的报告情况

转载于:https://www.cnblogs.com/xujian2016/p/5466250.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值