Get the sum only from specific cells in MySQL?

MySQLMySQLi Database

For only specific cells, set a condition with WHERE and use aggregate function SUM() to add. Let us first create a table −

mysql> create table DemoTable1370
   -> (
   -> StudentName varchar(20),
   -> Marks int
   -> );
Query OK, 0 rows affected (0.87 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1370 values('Adam Smith',56);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1370 values('Chris Brown',67);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1370 values('Adam Smith',69);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1370 values('David Miller',98);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1370 values('John Smith',59);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1370 values('Adam Smith',79);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1370 values('Chris Brown',77);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1370;

This will produce the following output −

+--------------+-------+
| StudentName  | Marks |
+--------------+-------+
| Adam Smith   |    56 |
| Chris Brown  |    67 |
| Adam Smith   |    69 |
| David Miller |    98 |
| John Smith   |    59 |
| Adam Smith   |    79 |
| Chris Brown  |    77 |
+--------------+-------+
7 rows in set (0.00 sec)

Here is the query that gets the sum from specific cells −

mysql> select sum(Marks) AS Total from DemoTable1370 where StudentName='Adam Smith';

This will produce the following output −

+-------+
| Total |
+-------+
|   204 |
+-------+
1 row in set (0.00 sec)
raja
Updated on 11-Nov-2019 09:19:59

Advertisements