显示Oracle查询中的总计,小计,百分比

时间:2012-12-11 18:50:38

标签: sql oracle10g

问题,

我的表格如下:

PID Category Year
1    AAA     2011
2    AAA     2012
3    BBB     2011
4    CCC     2010
5    CCC     2011
6    CCC     2012

我需要将输出显示为:

Subtotal Total Category  Year   Percentage
1         1      CCC      2010    100%
1         2      AAA      2011    50%
1         2      BBB      2011    50%
1         2      AAA      2012    50%
1         2      CCC      2012    50%

小计是特定年份的该类别的计数。 总计是特定年份的计数,包括所有类别。 百分比是小计/总计* 100

2 个答案:

答案 0 :(得分:7)

select subtotal, 
       total,
       category, 
       year,
       subtotal / total * 100 as percentage
from (
  select count(*) over (partition by category, year) as subtotal,
         count(*) over (partition by year) as total,
         category,
         year
  from the_unknown_table
) t
order by year;

答案 1 :(得分:4)

您想使用Windows /分析函数:

select subtotal,
       sum(subtotal) over (partition by year) as Total,
       category, year,
       (cast(subtotal*100.0/sum(subtotal) over (partition by year)  as varchar(255))+'%'
       ) as Percentage
from (select year, category, count(*) as subtotal
      from t
      group by year, category
     ) t