Reputation: 569
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?
Upvotes: 1
Views: 5380
Reputation: 15057
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>
Upvotes: 2
Reputation: 135
TRY:::
SELECT ROUND ( CAST ( SUM (quantity * calories) AS DECIMAL(10,4))) AS calories
FROM tableName;
Upvotes: 2
Reputation: 9070
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;
Upvotes: 1