Getting incorrect answer to formula when adding column to table in SQL

社会主义新天地 提交于 2021-01-29 05:36:48

问题


My table looks like this:

     error |  num  |    date    
    -------+-------+------------
       274 | 38431 | 2016-07-01
       389 | 54811 | 2016-07-02
       401 | 54465 | 2016-07-03

I want to calculate on which dates the 'error' was more than 1% of the 'num'.

Currently I'm trying to do this with this expression:

select date, error, num, (100 * (error / num)) as percentage 
from DD 
limit 3;

The result I'm getting is incorrect:

        date    | error |  num  | percentage 
    ------------+-------+-------+------------
     2016-07-01 |   274 | 38431 |          0
     2016-07-02 |   389 | 54811 |          0
     2016-07-03 |   401 | 54465 |          0

I get the same incorrect result if I take out the 100*.

With the solution below,

    select DD.*, (100.0 * error/num) as percentage from DD where (100.0 * error /num) > 1.0 

I get a correct top row but the rest incorrect:

     error |  num  |    date    |      percentage      
    -------+-------+------------+----------------------
    1265 | 54642 | 2016-07-17 |   2.3150689945463197
     274 |   274 | 2016-07-01 | 100.0000000000000000
     389 |   389 | 2016-07-02 | 100.0000000000000000

I checked the date 2016-07-01 and it has 274 error but the num is much higher. Why would it work for the top row but not for the rest?


回答1:


Use 100.0 instead of 100 to avoid integer division:

select dd.*, (100.0 * error / num) as percentage
from dd
where (100.0 * error / num) > 1.0;



回答2:


I think you just want a where clause with arithmetic:

select dd.*
from dd
where error > num / 100;

If you want the percentage, be careful about integer division:

(error * 100.0 / num)


来源:https://stackoverflow.com/questions/53906405/getting-incorrect-answer-to-formula-when-adding-column-to-table-in-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!