I have the following table:
+------------------+
| ColumnName |
+------------------+
| 1 Slap 开发者_StackOverflow中文版 |
+------------------+
| 13 Slap |
+------------------+
| 2 Slap |
+------------------+
With only MySQL how can I parse that ColumnName to only grab the numerical value and add them all up?
The output of the query should be 16 if doing it on the above table.
SELECT SUM(CAST(ColumnName as SIGNED)) FROM TableName
(or UNSIGNED
if you don't have any negative numbers)
Edit: Test data to satisfy the skeptics.
mysql> select * from testtable;
+---------+
| testcol |
+---------+
| 1 Slap |
| 13 Slap |
| 2 Slap |
+---------+
3 rows in set (0.00 sec)
mysql> select sum(cast(testcol as unsigned)) from testtable;
+--------------------------------+
| sum(cast(testcol as unsigned)) |
+--------------------------------+
| 16 |
+--------------------------------+
1 row in set, 3 warnings (0.00 sec)
mysql>
SELECT SUM(CAST(LEFT(ColumnName, INSTR(ColumnName, ' ')) as SIGNED))
FROM Table
精彩评论