I have one table like below query
mysql> select *from DemoTable;
This will produce the following output −
+--------------------+
| ListOfValues |
+--------------------+
| 20, 10, 40, 50, 60 |
+--------------------+
1 row in set (0.00 sec)
Expected output is below.
+----------+
| TotalSum |
+----------+
| 180 |
+----------+
1 row in set (0.00 sec)
I tried below examples but not working any one.
SELECT SUM(replace(ListOfValues, ',', '')) as TotalSum FROM DemoTable;
Here only first value came to in output, sum is not working.
+----------+
| TotalSum |
+----------+
| 20 |
+----------+
1 row in set (0.00 sec)
Can any one help please. I was tried so many examples taken from stackoverflow but no use.
2
Answers
As mentioned in comments you should redesign your database to not use comma seperated lists in a column.
If that is not possible, here is a workaround using
json_table
:Demo here
If there are duplicated
ListOfValues
then an auxiliary column can be used to provide a unique sequential number for each row :check demo : https://dbfiddle.uk/gcUbdS0U
You can use prepared statements.
Schema (MySQL v5.7)
View on DB Fiddle