如何在 MySQL 中显示列 Amount 中同一价格的两个不同求和?


为此,您可以使用 case 语句。我们首先创建一个表 -

mysql> create table DemoTable1794
     (
     Amount int
     );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable1794 values(100);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1794 values(80);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1794 values(320);
Query OK, 1 row affected (0.00 sec)

使用 select 语句从表中显示所有记录 -

mysql> select * from DemoTable1794;

这将生成以下输出 -

+--------+
| Amount |
+--------+
|    100 |
|     80 |
|    320 |
+--------+
3 rows in set (0.00 sec)

以下是显示列 Amount 中同一价格的两个不同求和的查询 -

mysql> select sum(Amount),
     sum( case when Amount < 150 then Amount else 0 end ) as SecondAmount
     from DemoTable1794;

这将生成以下输出 -

+-------------+--------------+
| sum(Amount) | SecondAmount |
+-------------+--------------+
|         500 |          180 |
+-------------+--------------+
1 row in set (0.00 sec)

更新于: 2019 年 12 月 23 日

125 次浏览

开启您的 事业

完成课程获得认证

开始
广告
© . All rights reserved.