简体   繁体   中英

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM