简体   繁体   English

如何在 SQL 中舍入百分比计算?

[英]How do I round a percentage calculation in SQL?

I want the below percentage calculation to be to 2 decimal places.我希望下面的百分比计算精确到小数点后两位。

 SELECT 
        (SUM(recovered)/SUM(confirmed_cases)*100) AS recovery_rate
    FROM corona 

However, the following does not work:但是,以下方法不起作用:

SELECT 
    ROUND((SUM(recovered)/SUM(confirmed_cases)*100), 2) AS recovery_rate
FROM corona

I suspect this is a data type issue since the ROUND() takes a number as its first argument and I'm guessing my SUM(...) percentage calculation isn't a number.我怀疑这是一个数据类型问题,因为 ROUND() 将数字作为它的第一个参数,我猜我的 SUM(...) 百分比计算不是数字。

What's the fix?有什么解决办法? Also, is there a general percentage function in SQL?另外,SQL 中是否有通用的百分比函数?

The problem is probably integer division -- but that depends on the database.问题可能是整数除法——但这取决于数据库。 You don't mention the database or the types of your columns, but 1/2 = 0, not 0.5 in a database such as SQL Server which does integer division您没有提到数据库或列的类型,而是 1/2 = 0,而不是在 SQL Server 等进行整数除法的数据库中的 0.5

This is easily fixed.这很容易解决。 Just change 100 to 100.0 :只需将100更改为100.0

SELECT ROUND(SUM(recovered) * 100.0 / SUM(confirmed_cases), 2) AS recovery_rate
FROM corona

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM