我有以下代码来计算PersonType的总死亡率和组。现在我想要一个列来计算每个死亡人数的百分比。即将每个人类的价值除以总死亡人数。SQL获取百分比
Select distinct persontype as PerSsonType, sum(fatalities_in_crash) as Total_Deaths
from [CarCrash].[Source_Data_Staging]
group by PersonType
我有以下代码来计算PersonType的总死亡率和组。现在我想要一个列来计算每个死亡人数的百分比。即将每个人类的价值除以总死亡人数。SQL获取百分比
Select distinct persontype as PerSsonType, sum(fatalities_in_crash) as Total_Deaths
from [CarCrash].[Source_Data_Staging]
group by PersonType
您可以使用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
。
非常感谢。有效。 – cookiemonster
可以跨加入这个查询与选择死亡的总和查询不进行分组:
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
标签您与您正在使用的数据库的问题。 –