PostgreSQL – 高效的选择不同项

huangapple go评论64阅读模式
英文:

Postgresql - efficient select distinct

问题

我有一个查询运行时间太长,我正在尝试简化它。我使用了https://explain.depesz.com/,显然我的“唯一”节点消耗了大量的计算时间。

我正在计算分区中的最大值,然后使用distinct on来保留最大值和其他列。

这是一个示例:

class student grade
1 A 0
1 B 10
1 C 11
1 D 7
2 E 20
2 F 18
2 G 19

基本上我想要每个教室的最高成绩:

class max_grade
1 11
2 20

我目前的做法是:

select distinct on (class)
       class, max_grade 
from (select max(grade) over (partition by class) as max_grade,
             student,
             class)

除了使用distinct on,是否有更好的方法来获得这个结果?

英文:

I have a query that is taking too much time to run and I am trying to simplify it. I used https://explain.depesz.com/, and apparently my "unique" node is consuming a lot of computation time.

I am calculating the maximum over a partition, and then using distinct on to keep the maximal value and the other column.

Here is an example:

class student grade
1 A 0
1 B 10
1 C 11
1 D 7
2 E 20
2 F 18
2 G 19

Basically I want the maximal grade per classroom:

class max_grade
1 11
2 20

what I currently do is:

select distinct on (class)
       class, max_grade 
from (select max(grade) over (partition by class) as max_grade,
             student,
             class)

Is there a better way to obtain this result than using distinct on?

答案1

得分: 1

这是最简单的聚合查询。

选择 班级, 最大(成绩) 从 表 根据 班级 分组
英文:

This is the simplest of aggregate queries.

SELECT class, MAX(grade) FROM tbl GROUP BY class

huangapple
  • 本文由 发表于 2023年7月3日 18:55:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76604080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定