【问题标题】:Perform arithmetic in SQL在 SQL 中执行算术运算
【发布时间】:2017-08-15 21:39:49
【问题描述】:

你能帮我解决这个问题吗?我有以下查询,它返回国家名称、每个国家的记录数和国家总数。我怎样才能让它也返回每个国家/地区相对于总数的百分比的列。理想的输出是这样的。

美国、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%)的国家/地区。

谢谢!

【问题讨论】:

标签: sql


【解决方案1】:

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

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

【讨论】:

  • 非常感谢!我只需将“数字”乘以 100 即可得到 5、12 等百分比。
【解决方案2】:

您应该手动操作:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      相关资源
      最近更新 更多