繁体   English   中英

SQL:获取具有一列(按列分组)为最大值的行

[英]SQL: Fetch rows having a column (group by column) being the MAX value

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

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

谢谢 !

先前的答案不太正确-您将不会获得其中两个具有相同计数的实例。 尝试一下-一旦理解了概念,第二个将很容易复制。

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)

备用查询:从任务a中选择a.subject_id,s.subject_name,COUNT(a.subject_id),主题s。从赋值GROUP BY subject_id中选择SELECT MAX(COUNT(1))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM