GROUP BY SQL Server 后总和的百分比
我有这些结果:
PersonID SUM(PA.Total)
-------------------------
1 75
2 75
3 15
4 15
5 60
6 60
像这样的表:
PersonID Total
------------------
1 50
2 50
3 10
4 10
5 40
6 40
1 25
2 25
3 5
4 5
5 20
6 20
这些是按人分组的.现在,我希望添加一列,其中包含根据所有总和计算得出的每个人的百分比.
These are grouped by the person. Now I'm looking to add a column with the percentages for each person calculated from the total of all of their sums.
例如:总和是 300,因此我需要这样的结果:
For example: the total sum is 300, and hence I need a result like this:
PersonID SUM(PA.Total) Percentage
--------------------------------------
1 75 25%
2 75 25%
3 15 5%
4 15 5%
5 60 20%
6 60 20%
我在网上查看了代码,并想出了一个修复方法,例如:
I have looked at code online and I have come up with a fix such as this:
SELECT
P.PersonID, SUM(PA.Total)
SUM(PA.Total) * 100 / [p] AS 'Percentage'
FROM
Person P
JOIN
Package PA ON P.PersonID = PA.PackageFK
CROSS JOIN
(SELECT SUM(PA.[Total]) AS [p]
FROM Package PA) t
GROUP BY
P.PersonID
但我不确定如何将交叉联接合并到联接以及已经分组/求和部分中.或者这是否完全正确.
But I'm unsure how to incorporate the cross join into the join as well as the already group/sum section. Or whether this is along the right lines altogether.
任何帮助将不胜感激 - SQL fiddle http://sqlfiddle.com/#!9/80f91/2
Any help would be appreciated - SQL fiddle http://sqlfiddle.com/#!9/80f91/2
推荐答案
你不需要 cross join
.只需使用窗口函数:
You don't need a cross join
. Just use window functions:
SELECT P.PersonID, SUM(PA.Total),
SUM(PA.Total) * 100.0 / SUM(SUM(PA.Total)) OVER () AS Percentage
FROM Person P JOIN
Package PA
ON P.PersonID = PA.PackageFK
GROUP BY P.PersonID;
请注意,此查询不需要 JOIN
:
Note that you do not need the JOIN
for this query:
SELECT PA.PersonID, SUM(PA.Total),
SUM(PA.Total) * 100.0 / SUM(SUM(PA.Total)) OVER () AS Percentage
FROM Package PA
GROUP BY PA.PersonID;
SQL Server 进行整数除法.我使用十进制数进行此类计算,因此它们更有意义.
SQL Server does integer division. I do such calculations using decimal numbers so they make more sense.
这里是一个 SQL Fiddle,有两个变化:
Here is a SQL Fiddle, with two changes:
- 数据库更改为 SQL Server.
- 总数存储为数字而不是字符串.
相关文章