为此,您可以将GROUP BY与ORDER BY子句一起使用。让我们首先创建一个表-
create table DemoTable1499 -> ( -> StudentName varchar(20), -> StudentMarks int -> );
使用插入命令在表中插入一些记录-
insert into DemoTable1499 values('Chris',56); insert into DemoTable1499 values('David',78); insert into DemoTable1499 values('Bob',98); insert into DemoTable1499 values('Chris',45); insert into DemoTable1499 values('David',98); insert into DemoTable1499 values('Bob',58);
使用select语句显示表中的所有记录-
Mysql> select * from DemoTable1499;
这将产生以下输出-
+-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 56 | | David | 78 | | Bob | 98 | | Chris | 45 | | David | 98 | | Bob | 58 | +-------------+--------------+ 6 rows in set (0.00 sec)
以下是汇总行值并对结果进行排序的查询-
select StudentName,sum(StudentMarks) as TotalSum from DemoTable1499 -> group by StudentName -> order by TotalSum desc;
这将产生以下输出-
+-------------+----------+ | StudentName | TotalSum | +-------------+----------+ | David | 176 | | Bob | 156 | | Chris | 101 | +-------------+----------+ 3 rows in set (0.00 sec)