2

I have the following table

CREATE table test
(
    random_number INT,
    band VARCHAR(255),
    member_name VARCHAR(255)
);

INSERT INTO test VALUES(2300,'Metallica', 'Kirk');
INSERT INTO test VALUES(2000,'Metallica', 'Lars');
INSERT INTO test VALUES(2500,'Metallica', 'James');
INSERT INTO test VALUES(2800,'Metallica', 'Roberto');
INSERT INTO test VALUES(100,'SkidRow', 'Sebastian');
INSERT INTO test VALUES(140,'SkidRow', 'Rachel');
INSERT INTO test VALUES(110,'SkidRow', 'Scott');
INSERT INTO test VALUES(150,'SkidRow', 'Dave');
INSERT INTO test VALUES(100,'SkidRow', 'Rob');
INSERT INTO test VALUES(500,'Motorhead', 'Lemmy');
INSERT INTO test VALUES(100,'Motorhead', 'Mikkey');
INSERT INTO test VALUES(200,'Motorhead', 'Phil');

How could I get the biggest random_number of each band and return something like this:

random_number |   band    | member_name
-----------------------------------------
     2800     | Metallica |  Roberto
     150      | SkidRow   |  Dave
     500      | Motorhead |  Lemmy
JosepB
  • 2,205
  • 4
  • 20
  • 40
  • Check out window functions: https://stackoverflow.com/questions/3800551/select-first-row-in-each-group-by-group – Dinu Mar 24 '19 at 11:53

3 Answers3

15

Use distinct on:

select distinct on (band) t.*
from test t
order by band, random_number desc;

Here is a db<>fiddle.

distinct on is a very handy Postgres extension. For performance on large datasets, you want an index on (band, random_number desc).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • The problem with this answer is that it orders the results based on the alphabetic order of the band name. In my case I wanted to have a DISTINCT name and at the same time results based on the descending random_number. I achieved it with nested SELECT: `select random_number, band from (select distinct on (band) t.* from test t order by band, random_number desc) as nested order by random_number desc;` [Here](https://dbfiddle.uk/?rdbms=postgres_10&fiddle=6296d47f8e0e5db9af33ed39c049ec5b) is the modified db<>fiddle – JacobTheKnitter Aug 09 '22 at 12:00
6

Find the maximum random_number by grouping and join to the table:

select t.* 
from test t inner join (
  select band, max(random_number) maxnum from test group by band
) g
on g.band = t.band and g.maxnum = t.random_number

See the demo

forpas
  • 160,666
  • 10
  • 38
  • 76
-1

Use MAX()

SELECT max(random_number), band FROM test GROUP BY band

See: https://rextester.com/BEZD44968

Result would be:

no  max band
1   2800 Metallica
2   500 Motorhead
3   150 SkidRow
xangr
  • 879
  • 14
  • 28