如何在 MySQL 中执行条件 GROUP BY 来提取?
我们先创建一个表格 −
mysql> create table DemoTable ( StudentName varchar(40), StudentMarks int ); Query OK, 0 rows affected (0.64 sec)
使用插入命令将一些记录插入到表格中 −
mysql> insert into DemoTable values('John',78); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('Chris',48); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('John',67); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Chris',89); Query OK, 1 row affected (0.15 sec)
使用选择语句从表格中显示所有记录 −
mysql> select *from DemoTable;
这将生成以下输出。在这里,我们有一些重复的学生名称,比如成绩为 78 和 67 的学生“约翰” −
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | John | 78 | | Chris | 48 | | John | 67 | | Chris | 89 | +-------------+--------------+ 4 rows in set (0.00 sec)
以下是执行条件 GROUP BY 并显示具有最大成绩的独特学生姓名(例如,学生“约翰”具有最大成绩 78)的查询 −
mysql> select StudentName,Max(StudentMarks) AS StudentMarks from DemoTable group by StudentName;
这将生成以下输出 −
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | John | 78 | | Chris | 89 | +-------------+--------------+ 2 rows in set (0.00 sec)
广告