3

您好我正在使用 Oracle SQL Developer 并试图在我的表上获取百分比。

我当前的查询是:

select 
  decode(grouping(life), 1, 'Total', life) as "LifeName", 
  sum(case 
        when task is not null and to_char(datee, 'MM') = '08' 
          and to_char(datee, 'YYYY') = '2013' 
        then 1 
        else 0 
      end) as "MonthStatus"
from life_lk, task_c
where life_lk.life_id = task_c.life_id
group by rollup(life)

我得到的当前输出是:

LifeName             MonthStatus
dog                     5
bear                    20
cat                     1
Fish                    4
Total                   30

但是,我希望输出为:

LifeName             MonthStatus           Percent
dog                     5                     16
bear                   20                     66
cat                     1                      3
Fish                    4                     13
Total                  30                    100

因此,对于月份状态下的每个单元格,我希望将数字除以在本例中为 30 的总数。该数字将随时间动态变化,因此我不能简单地除以 30。

对不起,看起来邋遢的桌子。我不知道如何让它们看起来整齐排列。

谢谢您的帮助

4

4 回答 4

3

分析函数 ratio_to_report() 可能对您有用。它给出了一个值与指定窗口的所有这些值之和的比率。

在你的情况下:

100* ratio_to_report(sum(...)) over ()

不过,我不确定在汇总的情况下它会如何工作。

http://docs.oracle.com/cd/E18283_01/server.112/e17118/functions142.htm

于 2013-08-28T20:51:44.040 回答
1

有两种简单的方法可以获得正确的结果,因为 ROLLUP 只是将总计相加,从而将每行相加两次:

将 PARTITION BY GROUPING(life) 添加到 ratio_to_report

或者简单地将结果乘以 200 而不是 100: 200*ratio_to_report(...)

于 2013-08-28T22:49:01.770 回答
1
 SELECT t1.lifename, t1.monthstatus, (t1.monthstatus / t2.total * 100) as prcent FROM
 (
 select 
   decode(grouping(life), 1, 'Total', life) as "LifeName", 
 sum(case 
    when task is not null and to_char(datee, 'MM') = '08' 
      and to_char(datee, 'YYYY') = '2013' 
    then 1 
    else 0 
  end) as "MonthStatus"
from life_lk, task_c
where life_lk.life_id = task_c.life_id
group by rollup(life) ) t1
 ,
(select sum(monthstatus) as total FROM life_lk) t2 ;

这应该可以,不过我可能把你的表格和列弄错了

于 2013-08-28T23:43:36.470 回答
0

我想你可以除以

SELECT COUNT (MonthStatus)    

得到你的porcentage。

于 2013-08-28T20:19:58.077 回答