converting varchar to number and sum gives error:

converting varchar to number and sum gives error:

我试图通过将其转换为数字来对此列求和,但这些值也有逗号,这是我查询中的错误来源:

SELECT date_trunc('day', to_date("date" , 'mm-dd-yyyy')) as day, 
"from merch", 
sum(CAST("amount " AS numeric)) as amount 
FROM tb 
GROUP BY 1,2 
ORDER BY 1,2;

我正在尝试获取每天每个“来自商品”的金额总和。

我得到的错误是:无效数字,值“,”,位置 1,类型:十进制

demo

使用replace(string,FromValue,ToValue)

注意:这假设您的金额为###,###.00 格式。如果不是,你可以 return 错误数据。

with tb AS 
(SELECT '1,000.01' as "amount", '01-01-2022' as "date",'z' as "from merch" UNION ALL
SELECT '10,000.02' as "amount", '01-01-2022' as "date",'z' as "from merch" UNION ALL
SELECT '100,000.02' as "amount", '02-01-2022' as "date",'y' as "from merch")

SELECT date_trunc('day', to_date("date" , 'mm-dd-yyyy')) as day, 
"from merch", 
sum(CAST(replace("amount",',','') AS numeric)) as amount 
FROM tb 
GROUP BY 1,2 
ORDER BY 1,2;

Demo 2 with decimal

sum(CAST(replace("amount",',','') AS decimal(10,2))) as amount 

假设您已正确识别问题。

我(不是最近)在评论中发现了幽默的交流:

  • 如果您需要对其进行数学运算,请将其存储为数字
  • 如果您永远不会对其进行数学运算,请将其存储为字符串
  • 如果两者都需要,则需要两列
  • 日期除外...将日期存储为日期期间并在其上使用日期函数...不是字符串 {shudder} 函数!
  • 和 AutoIncrements 可以是数字(尽管我们永远不应该对它们进行数学运算)

@xQbert——此后将被称为“xQbert 的剃刀”