0

如何在此查询周围包装 DECODE 以处理零除数而不计算分母总和两次?thedate除了四舍五入的百分比之外,我不想返回任何内容。

SELECT thedate, ROUND (100*
  SUM( case when TRUNC(ACTIVITY_END_DATE) <= thedate
     AND TRUNC(ACTIVITY_END_DATE) >= add_months( trunc(thedate,'mm'), -12) 
     AND trunc(ACTIVITY_END_DATE) <= trunc(ACTIVITY_NEED_DATE) 
     AND SYSDATE  >=  trunc(thedate,'mm') then 1 else 0 end )  
  /
  SUM( case when TRUNC(ACTIVITY_END_DATE) <= thedate 
     AND TRUNC(ACTIVITY_END_DATE) >= add_months( trunc(thedate,'mm'), -12) 
     AND SYSDATE  >=  trunc(thedate,'mm') then 1 else 0 end ) ) as OTR12 
       FROM TEST
       cross join (  select add_months(last_day(SYSDATE), level-7) as thedate 
       from dual connect by level <= 12  )  
       GROUP BY thedate 
       ORDER BY thedate 

似乎使用解码,我必须做两次分母求和
DECODE(denominator_summation,0,NULL, numerator_summation / denominator_summation)

4

3 回答 3

1

使用有子句:

having 
SUM( case when TRUNC(ACTIVITY_END_DATE) <= thedate 
 AND TRUNC(ACTIVITY_END_DATE) >= add_months( trunc(thedate,'mm'), -12) 
 AND SYSDATE  >=  trunc(thedate,'mm') then 1 else 0 end ) ) as OTR12 
   FROM TEST
   cross join (  select add_months(last_day(SYSDATE), level-7) as thedate 
   from dual connect by level <= 12  )
> 0
于 2013-04-03T21:58:36.730 回答
1
SELECT 
  thedate, 
  ROUND (
    100 * SUM( 
       case when TRUNC(ACTIVITY_END_DATE) <= thedate
       AND TRUNC(ACTIVITY_END_DATE) >= add_months( trunc(thedate,'mm'), -12) 
       AND trunc(ACTIVITY_END_DATE) <= trunc(ACTIVITY_NEED_DATE) 
       AND SYSDATE  >=  trunc(thedate,'mm') then 1 else 0 end 
    ) / nullif(SUM( 
       case when TRUNC(ACTIVITY_END_DATE) <= thedate 
       AND TRUNC(ACTIVITY_END_DATE) >= add_months( trunc(thedate,'mm'), -12) 
       AND SYSDATE  >=  trunc(thedate,'mm') then 1 else 0 end 
    ), 0) 
  ) as OTR12 
FROM 
  TEST
  cross join (  
     select add_months(last_day(SYSDATE), level-7) as thedate 
     from dual connect by level <= 12  
  )  
GROUP BY thedate 
ORDER BY thedate 
于 2013-04-03T22:08:53.820 回答
0

使用子查询怎么样?

select thedate, (case when denom <> 0 then round(100*num/denom) end)
from (SELECT thedate,
             SUM( case when TRUNC(ACTIVITY_END_DATE) <= thedate
                            AND TRUNC(ACTIVITY_END_DATE) >= add_months( trunc(thedate,'mm'), -12) 
                            AND trunc(ACTIVITY_END_DATE) <= trunc(ACTIVITY_NEED_DATE) 
                            AND SYSDATE  >=  trunc(thedate,'mm') then 1 else 0
                  end )   as num,
             SUM( case when TRUNC(ACTIVITY_END_DATE) <= thedate 
                        AND TRUNC(ACTIVITY_END_DATE) >= add_months( trunc(thedate,'mm'), -12) 
                        AND SYSDATE  >=  trunc(thedate,'mm') then 1 else 0 end ) ) as OTR12 
        FROM TEST cross join
             (  select add_months(last_day(SYSDATE), level-7) as thedate 
                from dual connect by level <= 12  )  
        GROUP BY thedate 
     ) t
order by thedate
于 2013-04-03T21:58:43.440 回答