如何在MySQL中僅顯示和為小於150的列值?按照降序排列結果


為此,可以使用子查詢。我們首先建立一個表 −

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

使用insert命令在表中插入一些記錄 −

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)

使用select語句顯示錶中的所有記錄。以下是查詢 −

mysql> select *from DemoTable844;

這將產生以下輸出 −

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

如何在MySQL中僅顯示和為小於150的列值

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

這將產生以下輸出 −

+----+--------+
| Id | Amount |
+----+--------+
|  3 |     60 |
|  4 |     40 |
|  6 |     24 |
+----+--------+
3 rows in set (0.26 sec)

更新時間:2019年9月3日

139次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告