统计查询-根据条件进行count的两种实现方式- oracle

Sql语句:

select b.departmentname, b.name,   
       count(case when b.businessstate='NOTSUBMIT' then 1  else null end ) NOTSUBMIT,   
        count(case when b.businessstate='ABANDONED' then 7  else null end ) ABANDONED,  
        count(b.id) allCounts  
from business b group by b.departmentname, b.name  

通过case when then else end这句话来限定条件,count进行统计。

另外,可以先建一张视图,通过sum来进行统计:

视图:

create or replace view view_business_statistics as  
select b.id, b.name as BUSINESSNAME,b.DEPARTMENTNAME,b.sldate as SLDATE, b.applydate as APPLYDATE,  
         decode(b.businessstate,'NOTSUBMIT',1,0) as NOTSUBMITNUM,  
         decode(b.businessstate,'APPROVING',1,0) as APPROVINGNUM,  
from business b;  

 

通过sum进行统计的sql语句:

select b.departmentname, b.name,   
       sum(b.NOTSUBMITNUM) NOTSUBMIT,   
       sum(b.ABANDONED) ABANDONED,  
       count(b.id) allCounts  
from business b group by b.departmentname, b.name  

建立视图使用oracle自带的decode关键字(相当于case when),重新给列复制0和1,使用sum得到统计总数。

建立视图的思想是提高灵活性。

 

posted @ 2017-11-23 08:45  ZRRJDD  阅读(5243)  评论(0编辑  收藏  举报