在 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:
select distinct on (team) id, team, pointsfrom seasonsorder by team, 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.