使用 MySQL 查詢從記錄中移除小數點並對其求和


使用方法 SUM() 的聚合函式和 REPLACE()。我們先建立一個表 -

mysql> create table DemoTable857(Price varchar(100));
Query OK, 0 rows affected (1.40 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable857 values('50.60');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable857 values('40.30.20');
Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable857 values('10.20');
Query OK, 1 row affected (0.69 sec)

使用 select 語句從表中顯示所有記錄 -

mysql> select *from DemoTable857;

將產生以下輸出 -

+----------+
| Price    |
+----------+
| 50.60    |
| 40.30.20 |
| 10.20    |
+----------+
3 rows in set (0.00 sec)

以下查詢可移除小數點並對記錄求和 -

mysql> select sum(replace(Price,'.','')) AS SumOfALl from DemoTable857;

將產生以下輸出 -

+----------+
| SumOfALl |
+----------+
| 409100   |
+----------+
1 row in set (0.03 sec)

更新於: 03-Sep-2019

375 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.