我使用以下查询;
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输出?
答案 0 :(得分:1)
TRY :::
SELECT ROUND ( CAST ( SUM (quantity * calories) AS DECIMAL(10,4))) AS calories
FROM tableName;
答案 1 :(得分:1)
使用浮点数进行计算时,最好使用decimal(m,d)数据类型而不是float / double,因为float和double都表示近似数值数据值,并且在计算时使用时容易出现舍入错误。
您的查询可以使用:
select round(cast(sum(quantity * calories) as decimal(8,1))) as calories
from tableName;
答案 2 :(得分:1)
您可以先将参数转换为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>
样本2与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>