问题描述
我有一张看起来像这样的桌子:
I have a table that looks something like this:
Name Year Value
A 2000 5
A 2001 3
A 2002 7
A 2003 1
B 2000 6
B 2001 1
B 2002 8
B 2003 2
用户可以根据年份范围进行查询,返回按名称分组的Value的总和,如此(假设查询年份为2000-2001):
The user can query based on a range of years, and it will return the sum of Value grouped by Name, as such (assume queried years are 2000 - 2001):
Name SUM(Value)
A 8
B 7
现在,我想插入一个计算字段,该字段输出所有年份的每个名称值的总和与所有值的总和的比率.基本上所有值的百分比分别归因于 A 和 B,例如:
Now, I wanted to insert a calculated field that outputs the ratio of the sum of the values of each name for ALL years to the sum of all values. Basically the percentage of all values attributed to A and B, respectively, like:
Name SUM(Value) % Of Total
A 8 0.484 (16 / 33)
B 7 0.516 (17 / 33)
请注意,尽管用户只查询了 2000-2001 年,但我希望计算使用所有年份的总和.我已经搜索和试验了几个小时,但我不知道怎么做.我只知道如何对查询的年份求和:
Note that even though the user queried only 2000-2001, I want the calculation to use the sum across all years. I've been searching and experimenting for hours and I cannot figure out how. I only know how to sum across the queried years like so:
SELECT `Name`, SUM(`Value`)/(SELECT SUM(`Value`) FROM `table1`) AS "% of Total"
FROM `table1`
WHERE `Year` BETWEEN 2000 AND 2001
GROUP BY `Name`;
推荐答案
您可以通过在 FROM 子句中使用子查询来计算总数(并从中计算出所需的百分比):
You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:
SELECT Name,
SUM(Value) AS "SUM(VALUE)",
SUM(Value) / totals.total AS "% of Total"
FROM table1,
(
SELECT Name,
SUM(Value) AS total
FROM table1
GROUP BY Name
) AS totals
WHERE table1.Name = totals.Name
AND Year BETWEEN 2000 AND 2001
GROUP BY Name;
请注意,子查询没有过滤年份的 WHERE 子句.
Note that the subquery does not have the WHERE clause filtering the years.
这篇关于如何根据另一个 SELECT 的值进行 SELECT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!