使用MySQL从一列中的所有值中获取最后3位数字的总和

由于我们需要最后3位数字的总和,因此我们需要将聚合函数SUM()与一起使用RIGHT()。让我们首先创建一个表-

mysql> create table DemoTable
(
   Code int
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable values(5464322);
mysql> insert into DemoTable values(90884);
mysql> insert into DemoTable values(23455644);
mysql> insert into DemoTable values(4353633);

使用select语句显示表中的所有记录-

mysql> select *from DemoTable;

这将产生以下输出-

+----------+
| Code     |
+----------+
|  5464322 |
|    90884 |
| 23455644 |
|  4353633 |
+----------+
4 rows in set (0.00 sec)

以下是查询以获取列中所有值的最后3位数字的总和-

mysql> select sum(right(Code,3)) AS SumOfLast3Digit from DemoTable;

这将产生以下输出-

+-----------------+
| SumOfLast3Digit |
+-----------------+
|            2483 |
+-----------------+
1 row in set (0.00 sec)
猜你喜欢