简化现有查询(带有子对子选择的子句)

时间:2016-02-17 09:35:19

标签: sql oracle

我有一些类似下面的查询,想要简化这些查询。 是否有更短的方法来获得相同的结果。 如果可能的话,我希望在没有with clause且不使用dual表的情况下执行此操作。 也许有分析功能。

with tab1 as
( select 
    DEPARTMENT1,DEPARTMENT2,DEPARTMENT3,DEPARTMENT4,DEPARTMENT5,DEPARTMENT6,DEPARTMENT7,DEPARTMENT8 
 from 
    RECLAMATION 
 where 
   RECLAMATIONDATE between to_Date('20150101','YYYYMMDD') and to_Date('20151231','YYYYMMDD')
)
select 
   (select count(*) from tab1 ) sumAll, 
   (select count(*) from tab1 where DEPARTMENT1=1) sum1, 
   (select count(*) from tab1 where DEPARTMENT2=1) sum2, 
   (select count(*) from tab1 where DEPARTMENT3=1) sum3, 
   (select count(*) from tab1 where DEPARTMENT4=1) sum4, 
   (select count(*) from tab1 where DEPARTMENT5=1) sum5, 
   (select count(*) from tab1 where DEPARTMENT6=1) sum6, 
   (select count(*) from tab1 where DEPARTMENT7=1) sum7, 
   (select count(*) from tab1 where DEPARTMENT8=1) sum8
from dual;
  

有8个部门专栏。如果部门涉及回收,则每个包含值1,否则包含0。

结果如下:

sumAll | sum1 | sum2 | sum3 | sum4 | sum5 | sum6 | sum7 | sum8
-------+------+------+------+------+------+------+------+-----
   100 |   14 |   71 |   53 |   18 |    0 |   19 |   17 |   88

给出了表结构,并且它不是重新设计它的选项。

2 个答案:

答案 0 :(得分:0)

使用case表达式进行条件计数:

select count(*),
       sum(case when DEPARTMENT1=1 then 1 else 0 end) as dep1,
       ...
       sum(case when DEPARTMENT8=1 then 1 else 0 end) as dep8
 from 
    RECLAMATION 
 where 
   RECLAMATIONDATE between to_Date('20150101','YYYYMMDD') and to_Date('20151231','YYYYMMDD')

答案 1 :(得分:0)

  

有8个部门专栏。如果部门涉及回收,则每个包含值1,否则包含0。

SELECT COUNT(*) AS SumAll,
       SUM( DEPARTMENT1 ) AS Sum1,
       SUM( DEPARTMENT2 ) AS Sum2,
       SUM( DEPARTMENT3 ) AS Sum3,
       SUM( DEPARTMENT4 ) AS Sum4,
       SUM( DEPARTMENT5 ) AS Sum5,
       SUM( DEPARTMENT6 ) AS Sum6,
       SUM( DEPARTMENT7 ) AS Sum7,
       SUM( DEPARTMENT8 ) AS Sum8
FROM   RECLAMATION
WHERE  EXTRACT( YEAR FROM RECLAMATIONDATE ) = 2015

注意,我使用EXTRACT过滤日期,因为您使用BETWEEN获取日期,包括2015-12-31T00:00:00,但它会忽略2015-12-31T00:00:01之间的日期和2015-12-31T23:59:59(我假设不是你所要求的)。