MySQL 查询按列分组并显示另一列中相似值的总和
mysqlmysqli database更新于 2025/11/8 0:44:17
为此,请使用 GROUP BY HAVING 子句。
首先我们创建一个表 −
mysql> create table DemoTable782 ( Name varchar(100), Score int ); Query OK, 0 rows affected (1.18 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable782 values('John',156);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable782 values('Carol',250);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable782 values('Bob',140);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('John',126);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable782 values('John',140);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Bob',280);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Bob',250);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable782 values('Carol',189);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable782 values('Carol',299);
Query OK, 1 row affected (0.21 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable782;
这将产生以下输出 -
+-------+-------+ | Name | Score | +-------+-------+ | John | 156 | | Carol | 250 | | Bob | 140 | | John | 126 | | John | 140 | | Bob | 280 | | Bob | 250 | | Carol | 189 | | Carol | 299 | +-------+-------+ 9 rows in set (0.00 sec)
以下是按列分组并显示相似值总和的查询 −
mysql> select Name,SUM(Score) AS Total from DemoTable782 group by Name HAVING Total > 500;
这将产生以下输出 -
+-------+-------+ | Name | Total | +-------+-------+ | Carol | 738 | | Bob | 670 | +-------+-------+ 2 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

