我想确定特定团队中ID最高的球员,ID最高的球员和ID最低的球员的名字。这是我目前拥有的sql。它有效,但是我想知道是否还有我不知道的更好/替代方法:
select max(player_id),
min(player_id),
substring(
max(
concat(
lpad(player_id::text, 10, '0'),
player_name))
from 11)
from players
where team_id = 201
group by team_id;
答案 0 :(得分:2)
order by
和limit
可能是最好的方法:
select p.*
from players p
where p.team_id = 201
order by p.team_id, p.player_id desc
fetch first 1 row only;
如果您希望所有(或部分)团队获得结果,请使用distinct on
:
select distinct on (teamp_id) p.*
from players p
where p.team_id = 201
order by p.team_id, p.player_id desc;