MySQL 转换为十进制 (5,2) 仍然 return 0

MySQL cast to decimal (5,2) does still return 0

我试图在此处获取客户 table 中德国客户的百分比: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

我正在使用这个查询:

SELECT cast((cast((SELECT COUNT(*) FROM Customers WHERE Country = "Germany") as DECIMAL(5,2))/cast((SELECT COUNT(*) FROM Customers) as DECIMAL(5,2))) AS DECIMAL(5,2)) AS PercentageGermans;

出于某种原因,我仍然返回 0,尽管将终止符的所有成分都转换为十进制 5,2。

我已经针对该主题搜索过 SO 并找到了这个答案:

在这里,我尝试进行的转换与我所做的几乎相同:

cast((select count(random_int) from test) as decimal(7,2))

正在将转换应用于完整子查询。它在那里工作,也可以在 fiddle 上看到: http://sqlfiddle.com/#!15/63252/37

但我不明白我的情况出了什么问题。

I'm trying to get the percentage of german customers inside the customers table.

我认为你夸大了这一点。我只想将您的查询表述为:

select avg(country = 'Germany') ratio_germans from customers

这会为您提供一个介于 01 之间的值,代表德国客户的比例。您可以通过将其乘以 100 将其转换为百分比。假设您想要一个带有 2 位小数的百分比,则:

select round(avg(country = 'Germany') * 100, 2) percent_germans from customers