【问题标题】:Get other columns(attribute) with max values获取具有最大值的其他列(属性)
【发布时间】:2020-08-05 16:08:27
【问题描述】:

我的数据框

ID      COURSE_ID SEC_ID SEMESTER YEAR  GRADE
00128   CS-101    1      Fall   2009    A
00128   CS-347    1      Fall   2009    A-
12345   CS-101    1      Fall   2009    C
....

我想在 2009 年秋季获得最大注册人数(count(id))的 course_id 和 sec_id。

所以,我试过了

select course_id, sec_id, enrollment
from (select course_id, sec_id, count(ID) as enrollment
    from takes
    where semester = 'Fall' and year = 2009
    group by course_id, sec_id)

但是,这将导致每个班级都有注册人。我只想显示注册人数最大的课程。我想我需要使用 ma​​x,但现在我需要使用此代码的子部分 from.(from subquery)

来解决它

++ 我可以使用have子句解决它吗? 如果可以的话,我将不胜感激。

感谢您的阅读。

【问题讨论】:

  • 轻松为您提供帮助:minimal reproducible example.
  • 如果两个值相同怎么办?
  • @GordonLinoff 在这个数据集中,没有重复!

标签: sql database oracle group-by greatest-n-per-group


【解决方案1】:

您可以筛选 2009 年秋季的课程,按 course_idsec_id 汇总,按每组的行数对结果进行排序,并使用行限制子句来获得最受关注的课程:

select course_id, sec_id, count(*) no_registrants
from takes
where semester = 'Fall' and year = '2009'
group by course_id, sec_id
order by no_registrants desc
fetch first 1 rows with ties

如果有的话,这允许顶级关系。如果您只想要一行,您可以将fetch first 1 rows with ties 更改为fetch first 1 rows only。您可能还想添加第二个排序条件以使结果具有确定性(否则,未定义的课程将出现在有联系的情况下)。


在 Oracle rank() 代替(或row_number() 禁止绑定):

select course_id, sec_id, no_registrants
from (
    select 
        course_id, 
        sec_id, 
        count(*) no_registrants,
        rank() over(order by count(*) desc) rn
    from takes
    where semester = 'Fall' and year = '2009'
    group by course_id, sec_id
) t
where rn = 1

【讨论】:

    【解决方案2】:

    根据我对您的要求的理解,您的查询只需修改即可获得正确的结果。

    只获取注册人数最多的一条记录。使用相同的查询,只需添加以下提到的更改:

    select course_id, sec_id, max(enrollment) as registrants
    from (select course_id, sec_id, count(ID) as enrollment
    from takes
    where semester = 'Fall' and year = 2009
    group by course_id, sec_id) as Rdet group by course_id,sec_id;
    

    这将根据您的要求为您提供正确的结果。

    【讨论】:

    • 这将适用于 sql server。你用的是哪个服务器?哪个版本?
    • Are you using which server - 问题被标记为Oracle
    【解决方案3】:

    您可以将子查询放在 CTE 中以重复使用它:

    with
    x as (
      select course_id, sec_id, count(*) as enrollment
      from takes
      where semester = 'Fall' and year = 2009
      group by course_id, sec_id
    )
    select *
    from x
    where enrollment = (select max(enrollment) from x)
    

    【讨论】:

    • 是的,我用'with'做的,这是一个使用from子句解决的问题。
    猜你喜欢
    • 2017-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    相关资源
    最近更新 更多