我有以下代码来计算总人数和按PersonType分组。现在我想要一个列来计算每个死亡事故的百分比。这是为每个人的类型取值并除以总死亡人数。
Select distinct persontype as PerSsonType, sum(fatalities_in_crash) as Total_Deaths
from [CarCrash].[Source_Data_Staging]
group by PersonType
答案 0 :(得分:2)
您可以使用ANSI标准窗口函数(包括SQL Server在内的大多数数据库都支持):
Select persontype as PerSsonType, sum(fatalities_in_crash) as Total_Deaths,
sum(fatalities_in_crash) * 1.0 / sum(sum(fatalities_in_crash)) over () as ratio
from [CarCrash].[Source_Data_Staging]
group by PersonType;
注意:您几乎不需要SELECT DISTINCT
GROUP BY
。 * 1.0
是因为某些数据库使用整数除法 - 这会为所有行生成0
。
答案 1 :(得分:1)
您可以将此查询与选择死亡总和而不进行分组的查询交叉加入:
SELECT persontype,
SUM(fatalities_in_crash) AS Total_Deaths,
SUM(fatalities_in_crash) / all_deaths AS percentage
FROM [CarCrash].[Source_Data_Staging]
JOIN (SELECT SUM(fatalities_in_crash) AS all_deaths
FROM [CarCrash].[Source_Data_Staging]) t
GROUP BY persontype