How to sum based on field value in MySQL?

MySQLMySQLi Database

To sum based on field values, use aggregate function SUM() along with CASE statement. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Price int,
   isValidCustomer boolean,
   FinalPrice int
   );
Query OK, 0 rows affected (0.23 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(20,false,40);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(45,true,10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(89,true,50);
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(Price,isValidCustomer,FinalPrice) values(200,false,100);
Query OK, 1 row affected (0.06 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+-----------------+------------+
| Id | Price | isValidCustomer | FinalPrice |
+----+-------+-----------------+------------+
| 1  | 20    | 0               | 40         |
| 2  | 45    | 1               | 10         |
| 3  | 89    | 1               | 50         |
| 4  | 200   | 0               | 100        |
+----+-------+-----------------+------------+
4 rows in set (0.00 sec)

Following is the query to sum based on field value in MySQL. Here, FinalPrice would be added for FALSE (0), whereas PRICE would be added for TRUE(1) −

mysql> select sum(case when isValidCustomer=true then Price else FinalPrice end) as TotalPrice from DemoTable;

This will produce the following output −

+------------+
| TotalPrice |
+------------+
| 274        |
+------------+
1 row in set (0.00 sec)
raja
Published on 20-May-2019 12:07:38
Advertisements