SQL case 语句的实践

来源:互联网 发布:ubuntu没有中文输入法 编辑:程序博客网 时间:2024/05/30 23:49

Case  和聚合函数的组合


       

select  custid, case when opendate>20160101 and opendate<20161231 then count(*) else o end as total  from customer_table group by custid, opendate       1


      

 select  custid  sum(case when opendate>20160101 and opendate<20161231 then 1 else o end ) as total from customer_table group by custid                             2      



select  custid, opendate,  case when opendate>20160101 and opendate<20161231 then count(*) else o end as total  from customer_table group by custid, opendate      3


注意语句1 是现以custid, opendate做了聚合,再选择部分聚合后的值计算count(*) , 逻辑和语句3一样, 只不过删除了opendate这个列, 此时custid仍有重复值。count(*) 计算的如果满足opendate>20160101 and opendate<20161231的值


语句2 和语句1的相差很大, 相当于对原始行做了过滤( where 处过滤),在进行聚合


这两句是聚合函数的使用位置引起的, 是在case 内部使用,还是在外部使用。










0 0
原创粉丝点击