case和内嵌视图

    现在很多程序员一般都愿意探索和争论究竟java平台还是.net平台哪个执行效率更高,特别是使用hibernate以后,更加不关注自己所写的sql语句的执行效率。
    而我认为,程序的核心就是要和数据库打交道,而数据库操作就离不开sql语句。因此,在程序设计中的数据处理方式和sql语句的编写就尤为重要。一个蠢笨的数据处理流程和一段执行效率很低的sql语句往往是影响系统速度的重要原因。

1、单条件case语句
case语句是很有用的,用case语句加内嵌视图,往往能用一个sql语句解决原来要用多段sql才能解决的问题。
   例子:员工表:employee字段:
             bianh            编号,主键
             bum_bianh    部门编号
             xingb            性别(1:男性,2:女性)
             xingm           姓名
             gongzi          工资

             部门表:department字段:
             bum_bianh    部门编号
             mingch         部门名称
  
   问题:用一个语句统计出某一部门的总人数,以及男性、女性的人数
         select department.mingch,count(employee.bianh),sum(case xingb when 1 then 1 else 0 end) as nanren_shu,
                                                sum(case xingb when 2 then 1 else 0 end) as nvren_shu
          from employee,department
          where employee.bum_bianh = department.bum_bianh
          group by department.mingch
          order by department.mingch
  
   注意:语句中用的是sum(),而不是count(),想想为什么?
  
   结果:
       mingch    nanren_shu     nvren_shu
       部门1       40                   29
       部门2       39                   21
       部门3       11                   27
   
2、多条件case语句
  
   问题:用一个语句统计出某一部门的总人数,以及男性中,工资高于和低于3000的人数,女性中,工资高于和低于3000的人数
  
   select department.mingch,count(employee.bianh),sum(case when xingb=1 and gongzi>=3000 then 1 else 0 end) as nanren_shu1,sum(case when xingb=1 and gongzi<3000 then 1 else 0 end) as nanren_shu2,sum(case when xingb=2 and gongzi>=3000 then 1 else 0 end) as nvren_shu1,sum(case when xingb=2 and gongzi<3000 then 1 else 0 end) as nvren_shu2                                        
   from employee,department
   where employee.bum_bianh = department.bum_bianh
   group by department.mingch
   order by department.mingch
   
3、内嵌视图
   我们都知道视图,所谓内嵌视图,就是在执行的时候才建立的视图。它是临时的,并不要真的用create view语句来建立一个视图。
   某一个sql查询都可以定义成内嵌视图,然后给这个内嵌视图命个名字,在此基础上再和别的表形成联合查询。并且,查询的结果,又可以再命名为一个新的内嵌视图的名字,多次嵌套都没问题。有些sql语句为什么写那么长,把人家几段语句执行的功能合成为一句就够了呢?就是用的这个办法。
  
   我要得到一个结果,就是在员工名单的基础上,增加一列显示:该部门的平均工资
  
   select employee.bianh,employee.xingm,employee.gongzi,bum_pingj.pingj_gongzi
   from employee,(select bum_bianh,avg(gongzi) as pingj_gongzi from employee group by bum_bianh) as bum_pingj
   where employee.bum_bianh = bum_pingj.bum_bianh
   order by employee.bianh
  
   为了说明原理,例子比较简单,但在实际中,你会发现这两项功能非常受用!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值