我有这张表的订单
+-----+--------+--------+-----------+-----------+
| id|order_id| price| tax| qty |
+-----+--------+--------+-----------+-----------+
| 5| 123| 231.40| 50.91| 1|
+-----+--------+--------+-----------+-----------+
| 6| 123| 210.74| 46.36| 1|
+-----+--------+--------+-----------+-----------+
此查询用于获取订单123的结果
SELECT Sum(price * qty) AS tot_sub,
( Sum(( price + tax ) * qty) ) AS tot
FROM products
WHERE order_id = 123
这就是结果
+-------+-----------------+
|tot_sub|tot |
+-------+-----------------+
|442.14 |539.4100000000001|
+-------+-----------------+
我期待tot
(539.41
)的完美价值
我知道浮点数的内部表示(通常)可能有一些错误,并且与确切的理论数不同。
在这种情况下,如果不使用ROUND函数,我可以编写更好的查询来避免此错误吗?
感谢
答案 0 :(得分:1)
使用cast as decimal
。
更改:
SELECT Sum(price * qty) AS tot_sub,
( Sum(( price + tax ) * qty) ) AS tot
FROM products
WHERE order_id = 123
致:
SELECT Sum(price * qty) AS tot_sub,
Sum( ( cast( price as decimal(10,2) )
+ cast( tax as decimal(10,2) ) ) * qty ) AS tot
FROM products
WHERE order_id = 123
请参阅 :
答案 1 :(得分:0)
SELECT Sum(price * qty) AS tot_sub,
Round( Sum(( price + tax ) * qty) ),2) AS tot
FROM products
WHERE order_id = 123