1

数据库名称 = 大学

table1: university_info
field = university_name, student_number
e.g. values:

university_name          student_number
USC                      12345
USC                      54321
UW                       23456
UW                       65432

table2: student_info
field = student_number, student_test_scores
e.g. values:

student_number           student_test_scores
12345                    50
12345                    60
54321                    70
54321                    80
23456                    90
23456                    92
65432                    90
65432                    100

我上面有两张桌子。让我们打电话给数据库大学。我想在第一次查询时解析并输出大学名称、学号和学生考试成绩。

Example of first query:
e.g result
USC   12345   50
USC   12345   60
USC   54321   70
USC   54321   80
UW    23456   90
UW    23456   92
UW    65432   90
UW    65432  100

在第二个查询中,我想要相同的输出,但这次学生的测试分数更高。

Example of second query:
USC 12345  60
USC 54321  80
UW  23456  92
UW  65432 100

一旦我们有最高的学生考试成绩,我们需要对第三次查询中的考试成绩进行平均,并输出最高学生考试成绩的平均值。

Example of third query:
Average test scores = 83

这是我到目前为止对第二个查询的内容。我不知道如何添加名称:

mysql> select student_info.student_number, student_info.student_test_scores
    -> from student_info
    -> where (student_number='12345' and student_test_scores > 50)
    -> or (student_number='54321' and student_test_scores > 70)
    -> or (student_number='23456' and student_test_scores > 90)
    -> or (student_number='65432' and student_test_scores > 90)
    -> ;
+----------------+---------------------+
| student_number | student_test_scores |
+----------------+---------------------+
|          12345 |                  60 |
|          54321 |                  80 |
|          23456 |                  92 |
|          65432 |                 100 |
+----------------+---------------------+
4 rows in set (0.00 sec)

我知道有一种更好的方法来完成上面的 3 个查询。我只是不知道该怎么做。谁能帮我?提前致谢。

4

1 回答 1

1

SQL 非常擅长这样做。

您需要使用 GROUP BY 语法以及聚合函数 MAX 和 AVG。

SELECT u.university_name, s.student_number, s.student_test_scores 
FROM student_info AS s
INNER JOIN university_info AS u ON s.student_number = u.student_number 
ORDER BY u.university_name, s.student_number, s.student_test_scores

SELECT u.university_name, s.student_number, MAX(s.student_test_scores) 
FROM student_info AS s
INNER JOIN university_info AS u ON s.student_number = u.student_number 
GROUP BY u.university_name, s.student_number
ORDER BY u.university_name, s.student_number

SELECT AVG(a.student_test_scores)
FROM (
    SELECT u.university_name, s.student_number, MAX(s.student_test_scores) AS student_test_scores
    FROM student_info AS s
    INNER JOIN university_info AS u ON s.student_number = u.student_number 
    GROUP BY u.university_name, s.student_number
) AS a
于 2012-11-09T13:50:38.563 回答