繁体   English   中英

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

[英]Display Total, Subtotal, Percentage in Oracle query

题,

我有这样的表:

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

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;

您想使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM