Mysql 如何在普通行中引用汇总汇总行
我想计算一个列值与查询中最低级别汇总类别之和的百分比。为此,我需要预先引用正常行中的汇总总和。这可能吗 简单示例表和数据:Mysql 如何在普通行中引用汇总汇总行,mysql,Mysql,我想计算一个列值与查询中最低级别汇总类别之和的百分比。为此,我需要预先引用正常行中的汇总总和。这可能吗 简单示例表和数据: 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)
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)
我认为这些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
谢谢。即使不能说这是一个好的解决方案,但它仍然为您提供了最接近的解决方案,您可以按照下面的方法进行尝试-
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';