开发者

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

开发者 https://www.devze.com 2023-02-16 19:20 出处:网络
I have the following table: +------------------+ |ColumnName| +------------------+ 1 Slap开发者_StackOverflow中文版|

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

精彩评论

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