[英]MySQL round() not working as expected with sum()
我正在使用以下查询;
select round(sum(quantity * calories)) as calories
from tableName;
其中数量和卡路里的类型为double,分别为1.00和110.50。 我期望输出为111,但是上面的查询却给了我110。但是,如果我执行如下所示的简单查询,
select round (110.50);
给我111作为输出。 我浏览了此Link ,并使用了如下查询:
select round(sum(cast(quantity * calories as char))) as calories
from tableName;
但这也对我不起作用,输出110。 有人可以告诉如何达到所需的111输出吗?
尝试:::
SELECT ROUND ( CAST ( SUM (quantity * calories) AS DECIMAL(10,4))) AS calories
FROM tableName;
使用浮点数进行计算时,最好使用十进制(m,d)数据类型,而不要使用float / double,因为float和double均表示近似数值数据值,并且在与计算一起使用时容易产生舍入误差。
对于您的查询,您可以使用:
select round(cast(sum(quantity * calories) as decimal(8,1))) as calories
from tableName;
您可以通过将参数首先强制转换为DECIMAL来实现。 然后我们将SUM / ROUND操作作为DECIMAL执行。
SELECT round( sum(
CAST(quantity AS DECIMAL(10,4)) *
CAST(calories AS DECIMAL(10,4)) ) ) AS calories
FROM tableName;
样品
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>
具有DECIMAL(10,2)的样本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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.