var sidebar_align = 'right';
var content_container_margin = parseInt('290px');
var sidebar_width = parseInt('270px');
Unanswered: Doubt with a simple query
I have the table table1 with the columns id, name, date;
I have the following data:
How can i write a select query that brings me back, when there is the same name with more than one date, only the record with the most recent date? Plus the records with only one date.
The result i want in my example would be:
select ename, max(date) from tbaname group by ename ;
this shld work right ?
"Greatest-N-Per-Group" queries are usually solved using window functions:
The above is ANSI standard SQL, so it also works with other DBMS that support
select id, name, date
select id, name, date,
row_number() over (partition by name order by date desc) as rn
where rn = 1
order by id, name;
Postgres also offers a proprietary way of doing this through the DISTINCT ON operator.
DISTINCT ON is usually faster then the solution using a window function.
select distinct on (name) id, name, date
order by name, date desc
More details in the manual: https://www.postgresql.org/docs/curr...l#SQL-DISTINCT
Last edited by shammat; 07-05-16 at