andersonbd1
andersonbd1

Reputation: 5386

How to select a column from a particular row in which I've used max on another column to determine the row

I want to determine the name of the player with the highest id on a particular team, the player with the highest id, and the player with the lowest id. This is the sql I currently have. It works, but I'm wondering if there are better/alternative ways that I don't know about:

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;

Upvotes: 0

Views: 32

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

order by and limit is probably the best way:

select p.*
from players p
where p.team_id = 201 
order by p.team_id, p.player_id desc
fetch first 1 row only;

If you want the result for all (or some) teams, use 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;

Upvotes: 2

Related Questions