【问题标题】:SQL: Efficient way to get group by results including all table columnsSQL:按结果分组的有效方法,包括所有表列
【发布时间】:2021-11-05 05:47:59
【问题描述】:

让我们考虑下面的一个简单表格。

id code marks grade
1 X 100 A
2 Y 120 B
3 Z 130 A
4 X 120 C
5 Y 100 A
6 Z 110 B
7 X 150 A
8 X 140 C

目标:获得每个年级的最高分,返回所有列。

id code marks grade
7 X 150 A
2 Y 120 B
8 X 140 C

如果我不想要idcode 列,这很简单

select grade, max(marks)
from table
group by grade;

在上述查询中获取idcode 列的最有效查询是什么?

我尝试了类似的方法,但没有成功

select * from table t
inner join
(select grade, max(marks)
from table
group by grade) a
on a.grade=t.grade;

【问题讨论】:

    标签: sql postgresql greatest-n-per-group


    【解决方案1】:

    在 Postgres 中,这种查询最有效的方法是使用(专有的)distinct on ()

    select distinct on (grade) *
    from the_table t
    order by grade, marks desc;
    

    【讨论】:

      【解决方案2】:

      您是否在寻找相关子查询?

      select t.*
      from t
      where t.marks = (select max(t2.marks) from t t2 where t2.grade = t.grade);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-22
        • 2020-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-29
        • 2012-12-08
        相关资源
        最近更新 更多