Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Get max value of each group with multiple columns [duplicate]

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
like image 378
JosepB Avatar asked Jan 23 '26 19:01

JosepB


1 Answers

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).

like image 95
Gordon Linoff Avatar answered Jan 26 '26 09:01

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!