Sum of data in varchar column

两盒软妹~` 提交于 2019-12-02 04:26:17

try this

select sum(cast(replace(SCENARIO1, ',', '.') as decimal(29, 10)))
from Mnt_Scenario_Exercice
where code_pere = '00000000';

If you couldn't convert your '4582014,00' into decimal, there's a chance you have different decimal separator on your server. You could look what it is or just try '.'

4582014,00 should be a decimal
try this (I assume that youre query is working) and changed convert(int into decimal)

select sum(convert(decimal(20,2),replace(SCENARIO1, ',', '.'))) from Mnt_Scenario_Exercice where code_pere='00000000'

The problem is due to the fact that the sum function isn't decoding SCENARIO1 as containing a CSV list of numbers. The way the sum function is usually used is to sum a lot of numbers drawn from multiple rows, where each row provides one number.

Try doing it in two steps. In step 1 convert the table into first normal form perhaps by UNPIVOTING. The 1NF table will have one number per row, and will contain more rows than the initial table.

The second step is to compute the sum. If you want more than one sum in the result, use GROUP BY to create groups, and then select a sum(somecolumn). This will yield one sum for each group.

Try this, I haven't got a way to test yet, but I will test and replace if incorrect.

SELECT sum(CAST (replace(SCENARIO1, ',', '') AS INT))
FROM   Mnt_Scenario_Exercice
WHERE  code_pere = '00000000';

EDIT: You can use a numeric for the cast if you need 4582014,00 to be 4582014.00

SELECT sum(CAST (replace(SCENARIO1, ',', '.') AS NUMERIC(10,2)))
    FROM   Mnt_Scenario_Exercice
    WHERE  code_pere = '00000000';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!