Home > Enterprise >  Query postgresql for max and group by
Query postgresql for max and group by

Time:03-10

I want get data in table by group and max.

example:

code date customercode description
CD01 2022-03-01 001 OK
CD02 2022-03-02 001 OK
CD03 2022-03-03 001 OK
CD04 2022-03-01 002 OK
CD05 2022-03-02 002 OK
CD06 2022-03-03 002 OK

result:

code date customercode description
CD03 2022-03-03 001 OK
CD06 2022-03-03 002 OK

How to query with PostgreSQL?

CodePudding user response:

You can use distinct on:

select distinct on(customercode) *
from table_name
order by customercode, date desc;

Fiddle

CodePudding user response:

If I am not wrong then you are asking on how to get the max date

Select * FROM yourtable WHERE date = (SELECT MAX(date) FROM yourtable) GROUP BY 'your desire columns' order by 'your desire columns'
  • Related