Question

I have a table

  id  |    name    |         ts
------+------------+---------------------
 3812 | name1      | 2014-05-01 00:10:02
 3900 | name1      | 2014-05-02 00:10:03
 3838 | name2      | 2014-05-01 00:10:08
 3893 | name3      | 2014-05-02 00:10:02
 3933 | name2      | 2014-05-02 00:10:14
 3977 | name3      | 2014-05-03 00:10:01
 3985 | name1      | 2014-05-03 00:10:02
 4006 | name2      | 2014-05-03 00:10:10
 3815 | name3      | 2014-05-01 00:10:02

I need perform a select which returns only latest(by 'table.ts') and only ONE entry for every DISTINCT value in field 'table.name'

  id  |    name    |         ts
------+------------+---------------------
 3977 | name3      | 2014-05-03 00:10:01
 3985 | name1      | 2014-05-03 00:10:02
 4006 | name2      | 2014-05-03 00:10:10

Help me for this task, please.

Was it helpful?

Solution 2

Assuming ID is incremented sequentially...

naming a table and column in the table with the same name may cause trouble later...

Select max(n.ID), n.name, max(n.TS) 
From Name n
group by n.name

However if ID is not sequential -- and assuming name and ts are UNIQUE...

Select a.id, a.name, a.ts
from name a
inner join (Select n.name, max(n.ts) mts from name n group by n.name) b 
  on A.Name = B.Name and A.TS = b.mts

OTHER TIPS

select id, name, ts
from (
  select id, 
         name, 
         ts, 
         max(ts) over (partition by name) as max_ts
  from the_table
) t
where ts = max_ts;
 select b.id, a.name, a.ts 
 from
 (
 select name, max(ts) ts  from table 
 group by name
 ) a
 left join table b on 
 a.id=b.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top