Get the sum of last 3 digits from all the values in a column with MySQL


Since we want the sum of last 3 digits, we need to use aggregate function SUM() along with RIGHT(). Let us first create a table −

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

Insert some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

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

Following is the query to get the sum of last 3 digits of all the values in a column −

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

This will produce the following output −

+-----------------+
| SumOfLast3Digit |
+-----------------+
|            2483 |
+-----------------+
1 row in set (0.00 sec)
raja
Published on 10-Oct-2019 15:58:36
Advertisements