在PostgreSQL中获取每个分组的第一行
给定一个表 seasons:
| id | 球队 | 积分 |
|---|---|---|
| 1 | Liverpool | 82 |
| 2 | Liverpool | 84 |
| 3 | Brighton | 34 |
| 4 | Brighton | 28 |
| 5 | Liverpool | 79 |
我们需要找出每支球队积分最高的记录。
期望的输出结果是:
| id | 球队 | 积分 |
|---|---|---|
| 3 | Brighton | 34 |
| 2 | Liverpool | 84 |
通过 SQL 编辑器,您可以运行如下查询:
12345678910select distinct on (team) id, team, pointsfrom seasonsorder BY id, points desc, team;关键点在于:
- 使用
desc关键字将points按从高到低排序 - 使用
distinct关键字告诉 Postgres 每支球队只返回一行记录
如果您更倾向于直接连接数据库,也可以通过 psql 或其他查询编辑器执行此查询。