SQL集合函数中case when then 使用技巧

来源:asp之家 时间:2011-09-30 11:54:59 

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

假设数据库有一张表名为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

标签:case,when,then,函数,sql
0
投稿

猜你喜欢

  • 使用access数据库时可能用到的数据转换

    2008-09-10 12:49:00
  • Hello! 404

    2010-09-06 13:37:00
  • [译]艺术和设计的差异 (2)

    2009-10-15 12:36:00
  • Oracle常用命令大全集

    2010-07-21 13:18:00
  • xhtml+css VS div+css

    2008-04-07 13:00:00
  • ORACLE 10g 安装教程[图文]

    2009-05-24 19:12:00
  • ASP怎么谈到应用到类的?

    2008-03-10 11:21:00
  • ASP中Request对象获取客户端数据的顺序

    2007-09-22 10:36:00
  • SQL Server 2005五个动态管理对象

    2009-02-24 17:41:00
  • 使用IP地址来统计在线人数方法

    2007-08-13 12:51:00
  • class和id命名探讨

    2007-10-16 17:55:00
  • 用蜜罐来阻止垃圾评论

    2007-11-06 12:35:00
  • 推荐9款很棒的网页绘制图表JavaScript框架脚本

    2009-04-15 12:13:00
  • 说说掌握JavaScript语言的思想前提

    2008-12-26 17:59:00
  • SQLServer 2005 实现数据库同步备份 过程-结果-分析

    2012-07-11 15:56:55
  • MySQL错误中文参照列表

    2010-09-30 14:41:00
  • Dreamweaver技巧十二招

    2009-07-05 18:53:00
  • 利用global.asa计划执行程序

    2008-03-05 12:49:00
  • SQL语句参考及记录集对象详解

    2008-11-25 11:47:00
  • 在flash中使用XML动态菜单

    2007-09-06 19:16:00
  • asp之家 网络编程 m.aspxhome.com