2017-08-15 94 views
0

你能幫我解決嗎?我有以下查詢返回國家名稱,每個國家的記錄數和國家總數。我怎麼能得到它也返回每個國家的百分比相對於總數的列。理想的輸出會是類似的。在SQL中執行算術運算

美國,25,100,25%......英國,28,100,28%......等等......

SELECT Country, COUNT(Country) AS number, (SELECT COUNT(Country) 
FROM[Customers]) AS total FROM [Customers] 
GROUP BY Country ORDER BY number DESC 

我試圖number/total AS percent但事與願違工作。顯然我做錯了什麼。

我希望能夠過濾超過一定百分比的國家,比如20%。

謝謝!

+0

您正在使用哪些DBMS? –

+0

可能的重複https://stackoverflow.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement – MatSnow

回答

1

使用派生表,它是一個帶有別名的子查詢。

select number/total AS percent 
from (
your query goes here 
) derivedTable 
+0

非常感謝!我只需要將「數字」乘以100即可得到像5,12等的百分比。 – rstreet

0

你應該做手工:

SELECT Country, COUNT(Country)*100/ (SELECT COUNT(Country) FROM[Customers]) AS total FROM [Customers] where total >20 
0

下面SQL會幫助你。

SELECT Country, COUNT(Country) AS number, (SELECT COUNT(Country) FROM[Customers]) AS total, ROUND(COUNT(Country) * 100.0/(SELECT COUNT(Country) FROM[Customers]), 1) FROM [Customers]