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

mysqlmysqli database

由于我们想要最后 3 位数字之和,因此我们需要使用聚合函数 SUM() 和 RIGHT()。让我们首先创建一个表 −

mysql> create table DemoTable
(
   Code int
);
Query OK, 0 rows affected (0.77 sec)

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

mysql> insert into DemoTable values(5464322);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(90884);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(23455644);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(4353633);
Query OK, 1 row affected (0.11 sec)

使用 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)

相关文章