2016-05-18 216 views
3

我有以下一段代碼來計算事件列中出現的次數。SQL - 計算計數百分比(列)

SELECT event, count(event) as event_count 
FROM event_information 
group by event 

event event_count 
a  34 
b  256 
c  45 
d  117 
e  3 

我想能夠像這樣計算每個行的百分比。

event event_count event_percent 
a  34   7.47 
b  256   56.26 
c  45   9.89 
d  117   25.71 
e  3   0.66 
+0

您正在使用哪個數據庫? – sgeddes

+1

獲取總事件並保存到變量。在原始select語句中使用該變量 –

回答

6
SELECT event, 
     count(event) as event_count, 
     count(event) * 100.0/(select count(*) from event_information) as event_percent 
FROM event_information 
group by event 
+0

直到我在where子句中添加日期範圍之後,它才能正常工作。正在計算的百分比是從整套數據中計算出來的,而不僅僅是日期範圍。正如你可以想象的那樣,由於event_count較低,所有百分比都很小。 –

+0

只需在內部選擇中添加相同的'where'子句。 –

1

大多數SQL方言支持ANSI標準的窗口功能。因此,您可以將查詢寫爲:

select event, count(*) as event_count, 
     count(*) * 100.0/ sum(count(*)) over() as event_percent 
from event_information 
group by event; 

窗口函數通常比子查詢和其他方法更高效。