SQL:获取具有列(逐列)的行为MAX值的行

时间:2015-02-19 17:11:09

标签: mysql sql database

我想知道如何检索与列的最大值匹配的行。

SCHEMA

assignments:
id  student_id   subject_id
1   10           1
2   10           2
3   20           1
4   30           3
5   30           3
6   40           2

students:
id  name
10   A
20   B
30   C

subjects:
id  name
1   Math
2   Science
3   English

查询: 提供SQL:

1. Display the names of the students who have taken most number of assignments
2. Display the names of the subjects which have been taken the most number of times

结果:

1. 
  A
  C

2. 
  Math
  English

谢谢!

1 个答案:

答案 0 :(得分:1)

之前的答案并不完全正确 - 你不会得到有两个具有相同计数的实例。试试这个 - 一旦理解了这个概念,第二个就很容易复制。

SELECT a.student_id, s.name, COUNT(a.subject_id) as taken_subjects
FROM assignments a
INNER JOIN students s ON a.student_id = s.id
GROUP BY a.student_id, s.name
HAVING COUNT(a.subject_id) = (SELECT COUNT(*) FROM assignments GROUP BY student_id LIMIT 1)

替代查询: SELECT a.subject_id,s.subject_name,COUNT(a.subject_id)FROM assignment a,subject s WHERE a.subject_id = s.subject_id GROUP BY a.student_id,s.subject_name HAVING COUNT(a.subject_id)=(SELECT MAX(COUNT(1))FROM FROM GROUP BY subject_id)