Select first row for each group in PostgreSQL
Given a table
We want to find the rows containing the maximum number of points per team.
The expected output we want is:
From the SQL Editor, you can run a query like:
_10select distinct_10on (team) id,_10team,_10points_10from_10seasons_10order BY_10id,_10points desc,_10team;
The important bits here are:
desckeyword to order the
pointsfrom highest to lowest.
distinctkeyword that tells Postgres to only return a single row per team.
This query can also be executed via
psql or any other query editor if you prefer to connect directly to the database.