MySQL - 具有相同 ID 的 SUM 行?
若要对具有相同 ID 的行求和,请使用 GROUP BY HAVING 子句。
让我们创建一个表 −
示例
mysql> create table demo84 -> ( -> id int, -> price int -> ) -> ; Query OK, 0 rows affected (0.60
借助 insert 命令将一些记录插入表中 −
示例
mysql> insert into demo84 values(1,2000); Query OK, 1 row affected (0.08 mysql> insert into demo84 values(1,2000); Query OK, 1 row affected (0.14 mysql> insert into demo84 values(2,1800); Query OK, 1 row affected (0.14 mysql> insert into demo84 values(2,2200); Query OK, 1 row affected (0.14 mysql> insert into demo84 values(3,1700); Query OK, 1 row affected (0.12
使用 select 语句从表中显示记录 −
示例
mysql> select *from demo84;
这将产生以下输出 −
输出
+------+-------+
| id | price |+------+-------+
| 1 | 2000 || 1 | 2000 |
| 2 | 1800 |
| 2 | 2200 || 3 | 1700 |
+------+-------+5 rows in set (0.00 sec)
以下是具有相同 id 行的求和查询 −
示例
mysql> select id,sum(price) as Total from demo84 -> group by id -> having sum(demo84.price) >=2000;
这将产生以下输出 −
输出
+------+-------+
| id | Total |+------+-------+
| 1 | 4000 || 2 | 4000 |
+------+-------+2 rows in set (0.00 sec)
广告