简体   繁体   中英

MySQL round() not working as expected with sum()

I'm using the following query;

select round(sum(quantity * calories)) as calories
from tableName;

where quantity and calories are of type double and having the values 1.00 & 110.50 respectively. I'm expecting an output of 111, but the above query is instead giving me 110. But if I execute a simple query like the below,

select round (110.50);

It's giving me 111 as the output. I went through this Link , and used a query like the following;

select round(sum(cast(quantity * calories as char))) as calories
from tableName;

but this one also not working for me and giving 110 as output. Can someone tell how to arrive at the desired output of 111?

TRY:::

SELECT ROUND ( CAST ( SUM (quantity * calories) AS DECIMAL(10,4))) AS calories
FROM tableName;

When you do calculations with floating point numbers, it is better to use decimal(m,d) datatype rather than float / double as both float and double represent approximate numeric data values and are prone to rounding errors when used with calculations.

For your query you can use:

select round(cast(sum(quantity * calories) as decimal(8,1))) as calories
from tableName;

You can accomplish this by casting the arguments first to DECIMAL. Then we performed the SUM / ROUND operation as DECIMAL.

SELECT round( sum( 
    CAST(quantity AS DECIMAL(10,4)) * 
    CAST(calories AS DECIMAL(10,4)) ) ) AS calories
FROM tableName;

sample

mysql> SELECT * FROM tableName;

+----+----------+----------+
| id | quantity | calories |
+----+----------+----------+
|  1 |        1 |    110.5 |
+----+----------+----------+
1 row in set (0,02 sec)

mysql> SELECT round( sum(
    ->     CAST(quantity AS DECIMAL(10,4)) *
    ->     CAST(calories AS DECIMAL(10,4)) ) ) AS calories
    -> FROM tableName;
+----------+
| calories |
+----------+
|      111 |
+----------+
1 row in set (0,00 sec)

mysql>

sample 2 with DECIMAL(10,2)

mysql> SHOW CREATE TABLE tableName\G
*************************** 1. row ***************************
       Table: tableName
Create Table: CREATE TABLE `tableName` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `quantity` decimal(10,1) DEFAULT NULL,
  `calories` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
1 row in set (0,00 sec)

mysql> SELECT * from tableName;
+----+----------+----------+
| id | quantity | calories |
+----+----------+----------+
|  1 |      1.0 |   110.50 |
+----+----------+----------+
1 row in set (0,00 sec)

mysql> select round(sum(quantity * calories)) as calories
    -> from tableName;
+----------+
| calories |
+----------+
|      111 |
+----------+
1 row in set (0,00 sec)

mysql>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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