如何用ORDER BY对MySQL中同名学生的分数求和?
为此,将ORDERBY与GROUPBY子句一起使用。我们首先创建一个带有学生姓名和分数的表格-
mysql> create table countRowValueDemo -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> StudentMathScore int -> );
以下是使用insert命令在表中插入记录的查询-
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Larry',45);
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Mike',56);
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',60);
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',40);
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',70);
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',80);
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',88);以下是使用select语句显示表中所有记录的查询-
mysql> select * from countRowValueDemo;
这将产生以下输出-
+-----------+-------------+------------------+ | StudentId | StudentName | StudentMathScore | +-----------+-------------+------------------+ | 1 | Larry | 45 | | 2 | Mike | 56 | | 3 | John | 60 | | 4 | David | 40 | | 5 | David | 70 | | 6 | John | 80 | | 7 | David | 88 | +-----------+-------------+------------------+ 7 rows in set (0.00 sec)
情况1:降序(总和)
以下是对名称相似的学生的分数求和的查询。结果将以降序显示-
mysql> select StudentName, -> sum(StudentMathScore) AS TOTAL_SCORE -> from countRowValueDemo -> group by StudentName -> order by sum(StudentMathScore) desc;
这将产生以下输出-
+-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | David | 198 | | John | 140 | | Mike | 56 | | Larry | 45 | +-------------+-------------+ 4 rows in set (0.00 sec)
情况2:升序(总和)
以下是对名称相似的学生的分数求和的查询。结果将以降序显示-
mysql> select StudentName, -> sum(StudentMathScore) AS TOTAL_SCORE -> from countRowValueDemo -> group by StudentName -> order by sum(StudentMathScore);
这将产生以下输出-
+-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | Larry | 45 | | Mike | 56 | | John | 140 | | David | 198 | +-------------+-------------+ 4 rows in set (0.00 sec)
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿