SUM a column based on a condition in MySQL



Let us first create a table −

mysql> create table DemoTable (    CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,    ProductAmount int,    CustomerCountryName varchar(10) ); Query OK, 0 rows affected (0.86 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(190,'US'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(200,'UK'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(1500,'AUS'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(2010,'US'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(7890,'UK'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(ProductAmount,CustomerCountryName) values(500,'US'); Query OK, 1 row affected (0.21 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------+---------------+---------------------+ | CustomerId | ProductAmount | CustomerCountryName | +------------+---------------+---------------------+ |          1 |           190 | US | |          2 |           200 | UK | |          3 |          1500 | AUS | |          4 |          2010 | US | |          5 | 7890 | UK | |          6 | 500 | US | +------------+---------------+---------------------+ 6 rows in set (0.00 sec)

Following is the query to sum a column based on a condition. Here, you want to sum the records for the customers with a country “US” −

mysql> select SUM(ProductAmount) AS Total_Amount from DemoTable where CustomerCountryName='US';

This will produce the following output −

+--------------+ | Total_Amount | +--------------+ | 2700 | +--------------+ 1 row in set (0.00 sec)
Updated on: 2019-10-03T07:55:03+05:30

607 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements