【问题标题】:Greatest n per group with multiple criteria for greatest每组最大 n,具有多个最大标准
【发布时间】:2013-08-23 01:43:35
【问题描述】:

我需要在多个学校中选择最大、最近或当前活跃的学期,并假设一所学校可能有多个并发学期(即,一个荣誉学生注册的学期,另一个非荣誉)。还需要考虑结束日期,因为荣誉学期可能有相同的开始日期,但可能是一年而不是一个学期,我想要这个学期。

代码如下所示:

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 可以轻松选择最大的 OR 最近学期,但我需要选择学生人数最多且最快结束的最近学期。

【问题讨论】:

  • 你确定你在使用 PostgreSQL 吗?

标签: postgresql greatest-n-per-group


【解决方案1】:

不确定我是否正确解释了您的问题。如果您提供包含主键和外键的表定义会更容易。

如果你想要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?

【讨论】:

    猜你喜欢
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2013-04-16
    • 2023-04-08
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多