开发者

MySQL parse Column to obtain a numerical section and add them up

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜