我有下表 t ,这是查询的结果:
user | value
A | 1
B | 2
A | 1
B | 4
我想计算下表:
user | sum(value) | percentage
A | 2 | 0.25
B | 6 | 0.75
获得百分比有点简单 - 谢谢@ lad2025
select sum(value)/(select sum(value) from t)
from t
group by user
问题是 t 已经是一个相当大的查询的结果,所以我想这样做而不重复t的名称。如果没有创建视图,这可能吗?
答案 0 :(得分:2)
您可以使用:
SELECT `user`, SUM(`value`) AS s,
SUM(`value`)/(SELECT NULLIF(SUM(value),0) FROM t) AS percentage
FROM t
GROUP BY `user`;
警告!我假设所有值都是积极的或0。
<强> DBFiddle Demo 强>
修改:
问题是t已经是一个相当大的查询的结果,所以我想这样做而不重复t的名称。
如果您使用的是MySQL 8.0或MariaDB,则可以使用SUM() OVER()
SELECT `user`, SUM(`value`) AS s, SUM(`value`)/SUM(SUM(`value`)) OVER()
FROM t
GROUP BY `user`;
<强> DBFiddle Demo2 强>
或使用CTE:
WITH t AS (
-- super complex query
)
SELECT `user`, SUM(`value`) AS s,
SUM(`value`)/(SELECT NULLIF(SUM(value),0) FROM t) AS percentage
FROM t
GROUP BY `user`;