Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find maximum value per group for all rows in SQL?

How to get the maximum value per group and get all rows of table?

create table out_pumptable(
name varchar(255),
    value double precision,
    anothercolumn varchar(255)
)

insert into out_pumptable
values ('Pump 1', 8000.0, 'Something1');

insert into out_pumptable
values ('Pump 1', 10000.0, 'Something2');

insert into out_pumptable
values ('Pump 1', 10000.0, 'Something3');

insert into out_pumptable
values ('Pump 2', 3043, 'Something4');

insert into out_pumptable
values ('Pump 2',4594, 'Something5');

insert into out_pumptable
values ('Pump 2', 6165, 'Something6');

Required output

    name    value   anothercolumn max
    Pump 1  8000.0  Something1    10000.0
    Pump 1  10000.0 Something2    10000.0
    Pump 1  10000.0 Something3    10000.0
    Pump 2  3043.0  Something4    6165.0 
    Pump 2  4594.0  Something5    6165.0
    Pump 2  6165.0  Something6    6165.0

My attempt

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select name, value 
from( select name, value, ROW_NUMBER() OVER(PARTITION BY name ORDER BY value desc) as rn
from out_pumptable ) as a
where rn = 1

>Solution :

You need MAX() window function:

SELECT *, 
       MAX(value) OVER (PARTITION BY name) "max"
FROM out_pumptable;

See the demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading