3

问题,

我有这样的表:

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

4

2 回答 2

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;
于 2012-12-11T18:54:12.877 回答
4

您想使用窗口/分析函数:

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
于 2012-12-11T18:53:59.807 回答