1

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
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
JosepB
  • 2,085
  • 4
  • 16
  • 36
  • 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

10

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,198,228
  • 53
  • 572
  • 709
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
  • 145,388
  • 9
  • 31
  • 69
0

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
  • 871
  • 14
  • 28