Display Column Values with Sum Less Than 150 in MySQL



For this, you can use subquery. Let us first create a table −

mysql> create table DemoTable844(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Amount int
);
Query OK, 0 rows affected (0.95 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable844(Amount) values(80);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable844(Amount) values(100);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable844(Amount) values(60);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable844(Amount) values(40);
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable844(Amount) values(150);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable844(Amount) values(24);
Query OK, 1 row affected (0.40 sec)

Display all records from the table using select statement. Following is the query −

mysql> select *from DemoTable844;

This will produce the following output −

+----+--------+
| Id | Amount |
+----+--------+
|  1 | 80     |
|  2 | 100    |
|  3 | 60     |
|  4 | 40     |
|  5 | 150    |
|  6 | 24     |
+----+--------+
6 rows in set (0.00 sec)

How to display only the column values whose sum is less than 150 in MySQL

mysql> select *from DemoTable844 tbl
   where (select sum(Amount) from DemoTable844 where Amount <= tbl.Amount order by Amount) < 150
order by Id;

This will produce the following output −

+----+--------+
| Id | Amount |
+----+--------+
|  3 |     60 |
|  4 |     40 |
|  6 |     24 |
+----+--------+
3 rows in set (0.26 sec)
Updated on: 2019-09-03T11:39:54+05:30

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements