集合函数中case when then 使用技巧
来源:互联网 发布:cheney算法 编辑:程序博客网 时间:2024/06/04 19:17
我们都知道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
参考:http://www.jb51.net/article/28222.htm
- SQL集合函数中case when then 使用技巧
- 集合函数中case when then 使用技巧
- SQL集合函数中case when then 使用技巧
- SQL集合函数中case when then 使用技巧
- SQL集合函数中case when then 使用技巧
- SQL集合函数中case when then 使用技巧
- SQL集合函数中利用case when then技巧
- sql中case when then使用实例
- mysql中case when then 的使用
- case when函数 case when then when then else end
- sql中case when then
- mysql中case-when-then和oracle的decode函数
- SQL中case when then的使用实例
- 数据库中case...when...then...end语句的使用
- 急CASE.WHEN.THEN.中使用别名的有关问题
- 【DB】MySQL中case when then 的使用
- mysql数据库中case...when...then...end语句的使用
- ORACLE case when 函数的使用技巧
- 如何在.net自定义控件引用外部资源
- 3个学生各学4门课,计算总平均分,并输出第n个学生成绩
- json_decode用法
- ensemble learning
- Visual Studio cannot debug managed applications because a kernel debugger is enabled on the system
- 集合函数中case when then 使用技巧
- 去掉webView白色背景
- DBUS入门与应用
- DWR详解——会变魔术的Javasript(一)
- C++面试之基础知识集锦
- strpbrk 函数解析
- 基于arm架构单片机的hadoop服务器尝试
- 断点续传的原理剖析与实例讲解
- Python多线程学习