Skip to content
Database

在 Postgres 中为每个组选择第一行

给定一个表 seasons

🌐 Given a table seasons:

编号球队积分
1利物浦82
2利物浦84
3布莱顿34
4布莱顿28
5利物浦79

我们想找出每个队得分最多的行。

🌐 We want to find the rows containing the maximum number of points per team.

我们期望的输出是:

🌐 The expected output we want is:

id球队积分
3布莱顿34
2利物浦84

SQL 编辑器 中,你可以运行如下查询:

🌐 From the SQL Editor, you can run a query like:

1
select distinct
2
on (team) id,
3
team,
4
points
5
from
6
seasons
7
order by
8
team,
9
points desc;

这里重要的部分是:

🌐 The important bits here are:

  • desc 关键词用来将 points 从高到低排序。
  • distinct 关键字告诉 Postgres 每个团队只返回一行数据。

如果你愿意直接连接到数据库,这个查询也可以通过 psql 或任何其他查询编辑器执行。

🌐 This query can also be executed via psql or any other query editor if you prefer to connect directly to the database.