2017-11-11 187 views
1

我有以下代碼來計算PersonType的總死亡率和組。現在我想要一個列來計算每個死亡人數的百分比。即將每個人類的價值除以總死亡人數。SQL獲取百分比

Select distinct persontype as PerSsonType, sum(fatalities_in_crash) as Total_Deaths 

    from [CarCrash].[Source_Data_Staging] 
group by PersonType 

enter image description here

+1

標籤您與您正在使用的數據庫的問題。 –

回答

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 DISTINCTGROUP BY* 1.0是因爲一些數據庫使用整數除法 - 這將產生所有行的0

+0

非常感謝。有效。 – cookiemonster

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