我有一个包含4个字段的MySQL表。它将用户存储多少次称为模块/动作组合。该表具有Composite Promary Key(CPK),由模块 - 动作 - 用户三元组组成。
analyze_cumulated
-----------------
module (CPK) VARCHAR,
action (CPK) VARCHAR,
user (CPK) INT,
times_called INT
我想编写一个查询来获取每个模块/操作对调用的次数,以及总调用的百分比。 我有这个查询工作正常但我想知道在主查询的SELECT部分中没有SELECT子查询是否还有其他方法可以做同样的事情。
SELECT
module,
SUM(times_called),
SUM(times_called)*100/(SELECT SUM(times_called) FROM analyze_cumulated)
FROM analyze_cumulated
GROUP BY module
答案 0 :(得分:2)
你可以加入它:
SELECT
module,
SUM(times_called),
SUM(times_called)*100/t.tot
FROM analyze_cumulated
JOIN (SELECT SUM(times_called) tot FROM analyze_cumulated) t
GROUP BY module;
第二个选项是使用临时变量:
SELECT SUM(times_called) into @tot FROM analyze_cumulated;
SELECT
module,
SUM(times_called),
SUM(times_called)*100/@tot
FROM analyze_cumulated
GROUP BY module;
答案 1 :(得分:1)
SELECT
module,
SUM(times_called) as Times_Called,
max((times_called/SUM(times_called))*100) as Percentage
FROM analyze_cumulated
GROUP BY module