为什么一个简单的查询在 BIgquery 中有效但在 PostgreSQL 中无效?

Why a simple query works in BIgquery but not PostgreSQL?

我写了下面的查询来计算 Postgresql 中的死亡百分比,结果为零,但 Bigquery 中的相同查询得到了正确的结果。任何人都可以有想法吗?谢谢!

SELECT 
location,
MAX(total_cases) AS Cases_total,
MAX(total_deaths) AS Death_total, (MAX(total_deaths)/MAX(total_cases))*100 AS DeathPercentange
FROM covid_deaths
WHERE continent IS NOT NULL 
GROUP BY location
ORDER BY DeathPercentange DESC;

不允许我插入屏幕截图,所以我有 link:

Same query in Bigquery

Query in PostgreSQL

数据库如下所示: The preview of the database

你做整数除法。只要 total_deaths < total_cases(这很可能是您的情况),结果将始终为 0。你应该做的是将至少一个操作数转换为浮点数或十进制,例如

(MAX(total_deaths)::decimal / MAX(total_cases))*100 AS DeathPercentange

结果没问题,你的操作是在大整数之间。结果只是一个整数。

112/9766 = 0 * 100 = 0

如果你想要一个数字作为结果,你必须将你的列转换为数字

SELECT 
location,
MAX(total_cases) AS Cases_total,
MAX(total_deaths) AS Death_total, (MAX(total_deaths)::numeric/MAX(total_cases)::numeric)*100 AS DeathPercentange
FROM covid_deaths
WHERE continent IS NOT NULL 
GROUP BY location
ORDER BY DeathPercentange DESC;