MySQL 如何在sql中将Varchar转换为Double?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14496090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Varchar to Double in sql?
提问by Jay Marz
I have problem with my query when I was trying to convert the varchar field to double (numeric). I have this sql statement:
当我尝试将 varchar 字段转换为 double(数字)时,我的查询出现问题。我有这个 sql 语句:
SELECT fullName, CAST(totalBal as numeric(9,2) FROM client_info ORDER BY totalBal DESC
Actually I want to display the values of totalBal
in descending order. But since that field is in varchar, the resultset is sometimes wrong. This is the resultset when I tried to query using this statement:
其实我想以totalBal
降序显示的值。但由于该字段在 varchar 中,结果集有时是错误的。这是我尝试使用此语句进行查询时的结果集:
SELECT fullName, totalBal FROM client_info ORDER BY totalBal DESC
Resultset is:
结果集是:
The sorting of totalBal
is not correct. So I decided to convert the varchar to numeric so that it might be sorted perfectly. Any idea?
排序totalBal
不正确。所以我决定将 varchar 转换为数字,以便它可以完美排序。任何的想法?
回答by John Woo
use DECIMAL()
or NUMERIC()
as they are fixed precision and scale numbers.
使用DECIMAL()
或NUMERIC()
因为它们是固定的精度和小数位数。
SELECT fullName,
CAST(totalBal as DECIMAL(9,2)) _totalBal
FROM client_info
ORDER BY _totalBal DESC
回答by Hammad Khan
This might be more desirable, that is use float instead
这可能更可取,即使用 float 代替
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC