我需要选择一些学校中规模最大,最近或当前有效的学期,并假设学校可以有多个并发学期(即一个学期授予学生注册,另一个学期为了不荣誉)。还需要考虑结束日期,因为荣誉术语可能具有相同的开始日期,但可能是一年而不是一个学期,我想要学期。
代码看起来像这样:
SELECT t.school_id, t.term_id, COUNT(s.id) AS size, t.start_date, t.end_date
FROM term t
INNER JOIN students s ON t.term_id = s.term_id
WHERE t.school_id = (some school id)
GROUP BY t.school_id, t.term_id
ORDER BY t.start_date DESC, t.end_date ASC, size DESC LIMIT 1;
这非常有效地找到当前或最近最活跃的术语,但我希望能够消除WHERE t.school_id = (some school id)
部分。
每个群体的标准最大n可以轻松选择最大或最近的学期,但我需要选择最新学期最快的学生。
答案 0 :(得分:0)
我不确定我是否正确解释了您的问题。如果您提供了包括主键和外键的表定义,则会更容易。
如果您希望每个学校the most recent term that ends soonest with the largest number of students
,可能会这样做:
SELECT DISTINCT ON (t.school_id)
t.school_id, t.term_id, s.size, t.start_date, t.end_date
FROM term t
JOIN (
SELECT term_id, COUNT(s.id) AS size
FROM students
GROUP BY term_id
) s USING (term_id)
ORDER BY t.school_id, t.start_date DESC, t.end_date, size DESC;
在此相关答案中对DISTINCT ON
的更多解释:
Select first row in each GROUP BY group?