在SQL中执行算术运算

问题描述:

你能帮我解决吗?我有以下查询返回国家名称,每个国家的记录数和国家总数。我怎么能得到它也返回每个国家的百分比相对于总数的列。理想的输出会是类似的。在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://*.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement – MatSnow

使用派生表,它是一个带有别名的子查询。

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

非常感谢!我只需要将“数字”乘以100即可得到像5,12等的百分比。 – rstreet

你应该做手工:

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

下面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]