[英]Convert INT to FLOAT in SQL
I have this Query :我有这个查询:
SELECT sl.sms_prefix, sum( sl.parts ) , cp.country_name, CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
FROM sms_log sl, sms_transaction st, country_prefix cp
WHERE st.customer_id =1
AND st.sendtime >=1329865200
AND st.sendtime <=1330037999
AND st.sms_trans_id = sl.trans_id
AND sl.sms_prefix = cp.prefix
AND st.customer_id = cp.customer_id
GROUP BY sl.sms_prefix
LIMIT 0 , 30
Result:结果:
sms_prefix sum( sl.parts ) country_name price total
==================================================================================
45 2 Denmark 0.01 0.019999999552965
63 3 Philippines 2 6
As you see the "total"
is not correct for Denmark
because sum( sl.parts )=2
Multiply with 0.01
the total should be 0.02
.如您所见,
Denmark
的"total"
不正确,因为sum( sl.parts )=2
乘以0.01
总数应为0.02
。
Price field is FLOAT
how I can CAST the total to float ?价格字段是
FLOAT
我如何才能将总数转换为浮动?
Regards,问候,
While @Heximal's answer works, I don't personally recommend it.虽然@Heximal 的回答有效,但我个人并不推荐它。
This is because it uses implicit casting.这是因为它使用隐式转换。 Although you didn't type
CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen.尽管您没有输入
CAST
,但在+
发生之前,需要将SUM()
或0.0
转换为相同的数据类型。 In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
.在这种情况下,优先顺序对你有利,两边都有一个浮动,而
+
的结果是一个浮动。 But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.但是
SUM(aFloatField) + 0
不会产生 INT,因为0
被隐式转换为 FLOAT。
I find that in most programming cases, it is much preferable to be explicit .我发现在大多数编程情况下,显式更可取。 Don't leave things to chance, confusion, or interpretation.
不要把事情留给机会、困惑或解释。
If you want to be explicit, I would use the following.如果你想明确,我会使用以下内容。
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...您可以尝试以下操作,看看会发生什么...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
在 oracle db 中有一个将 int 转换为 float 的技巧(我想,它也应该在 mysql 中工作):
select myintfield + 0.0 as myfloatfield from mytable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.