[英]Sum varchar field in SQL
I have a Varchar field for gross, the field has something like $1,000, $190, $2,900 我有一个用于总计的Varchar字段,该字段的内容类似于$ 1,000,$ 190,$ 2,900
I need to sum this column, should I alter the column to INT? 我需要对该列求和,我应该将该列更改为INT吗? and then use a regex to remove the $?
然后使用正则表达式删除$? Any suggestions.
有什么建议么。
You should fix the database so numbers are stored as numbers, not as strings. 您应该修复数据库,以便将数字存储为数字而不是字符串。 But, to do the sum, you can try:
但是,要求和,您可以尝试:
select sum(replace(replace(gross, ',', ''), '$', '') + 0)
This will convert your examples to a number and add them up. 这会将您的示例转换为数字并将其加起来。 If something is in a different format, it will silently produce a
0
for that value. 如果某种格式不同,它将默默地为该值产生一个
0
。
By the way, "gross" is an apt name for a field varchar field containing a number. 顺便说一句,“ gross”是包含数字的varchar字段的恰当名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.