您可以先鑄造參數DECIMAL做到這一點。然後我們以DECIMAL的形式執行SUM/ROUND操作。
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>
是否正在施加在單個記錄或整個表這個查詢?你能否給我們提供樣本數據以顯示一些背景? –
是的,我正在將它應用於單個記錄。 – karthi
已知浮點運算在編程語言(包括MySQL)中並不準確。我的猜測是,有輕微的變化,導致整輪下降,而不是。我不會因此而失眠;如果你有一個真正的桌子,並且遇到嚴重的舍入問題,那麼更新你的問題。 –