Update the table by calculating the sum and display the result as last column value

MySQLMySQLi Database

Use a variable to store SUM(total) and update it with the UPDATE command. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value int
);
Query OK, 0 rows affected (0.61 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value) values(70);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(Value) values(100);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Value) values(150);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Value) values(250);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Value) values(60);
Query OK, 1 row affected (0.22 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
|  1 | 70    |
|  2 | 100   |
|  3 | 150   |
|  4 | 250   |
|  5 | 60    |
+----+-------+
5 rows in set (0.00 sec)

Following is the query to set the sum in a variable and display the result as last column value −

mysql> set @Total=(select sum(Value) from DemoTable);
Query OK, 0 rows affected (0.00 sec)
mysql> update DemoTable
   set Value= @Total
   where Id=5;
Query OK, 1 row affected (0.16 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
|  1 |    70 |
|  2 |   100 |
|  3 |   150 |
|  4 |   250 |
|  5 |   630 |
+----+-------+
5 rows in set (0.00 sec)
raja
Published on 04-Oct-2019 08:38:18
Advertisements