如何引用正常行中的汇总汇总行

时间:2015-07-29 05:29:19

标签: mysql

我想计算列值与查询中最低级别汇总类别之和的百分比。为此,我需要预先引用正常行中的累计和。这可能吗? SQLFiddle

简单的示例表和数据:

create table test
  (category1 integer,
   category2 integer,
   amount double);

insert into test values
   (1,1,300),
   (1,1,400),
   (1,2,200),
   (1,2,500),
   (1,2,100),
   (2,1,300),
   (2,2,200),
   (2,2,500);

使用汇总查询数据:

select category1, category2, sum(amount) from test group by category1, category2 with rollup;   

category1   category2   sum(amount)
1           1           700
1           2           800
1           (null)      1500
2           1           300
2           2           700
2           (null)      1000
(null)      (null)      2500

结果我想实现:

category1   category2   sum(amount)  percent
1           1            700          46.6   -- 700/1500*100
1           2            800          53.3   -- 800/1500*100
1           (null)      1500         100.0
2           1            300          30.0   -- 300/1000*100
2           2            700          70.0   -- 700/1000*100
2           (null)      1000         100.0
(null)      (null)      2500         (doesn't matter)

2 个答案:

答案 0 :(得分:1)

我认为这些SQL对你有用

 select nn.category1,nnn.category2, round((val/tot)*100, 1) as amount from 
    (
    select t1.category1, sum(t1.amount) as tot from test t1 
    group by category1
    ) as nn
    join
    (
    select category1, category2, sum(amount) as val
    from test group by category1, category2 with rollup
      ) as nnn on  nn.category1 = nnn.category1 

sql fiddle

谢谢。

答案 1 :(得分:1)

即使不能说这是一个很好的解决方案,但它仍然为您提供最近的解决方案,您可以按照以下方式尝试 -

SELECT a.category1, a.category2, a.amt,round(a.amt/if(b.category1 is not null,b.amt,1)*100,2) 'Percentage' 
FROM 
(
SELECT category1, IFNULL(category2,'sub-total') category2, SUM(amount) amt 
FROM test GROUP BY category1, category2 WITH ROLLUP
) a 
    left join 
(
SELECT category1, IFNULL(category2,'sub-total') category2, SUM(amount) amt 
    FROM test GROUP BY category1, category2 WITH ROLLUP
) b 
on .category1=b.category1 and b.category2='sub-total';