Effective way to add integers based on table values in MySQL?

MySQLMySQLi Database

You need to use GROUP BY clause. Let us first create a −

mysql> create table DemoTable1443
   -> (
   -> StudentId int,
   -> StudentScore int
   -> );
Query OK, 0 rows affected (0.42 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1443 values(100,78);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1443 values(101,89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1443 values(100,88);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1443 values(101,97);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select −

mysql> select * from DemoTable1443;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentScore |
+-----------+--------------+
|       100 |           78 |
|       101 |           89 |
|       100 |           88 |
|       101 |           97 |
+-----------+--------------+
4 rows in set (0.00 sec)

Following is the query to add integers based on table values −

mysql> select StudentId,sum(StudentScore) from DemoTable1443
   -> group by StudentId;

This will produce the following output −

+-----------+-------------------+
| StudentId | sum(StudentScore) |
+-----------+-------------------+
|       100 |               166 |
|       101 |               186 |
+-----------+-------------------+
2 rows in set (0.00 sec)
raja
Published on 12-Nov-2019 11:29:41
Advertisements