简体   繁体   中英

How to get the latest records of the multiple values of same column in PostgreSQL?

I have a database with following structure

 url  update_time                 dns_time
 -------------------------------
 url1  2013-04-05 08:03:23       0.897
 url2  2013-09-03 08:03:45       0.765
 url1  2013-08-23 09:23:34       2.457
 url3  2013-08-34 09:45:47       1.456
 //and so on

Now I want to retrieve only latest records of each url. How to achieve this using PostgreSQL select query.

I tried using

 select url,
        update_time,
        dns_time 
 from dns_lookup_table 
 where url in('url1','url2','url3') 
 order by desc limit 1

But it is giving me the url3 latest value that is last record. I tried with desc limit 3 for getting latest values of all 3 urls. I want to retrieve the latest records of url1 , url2 , url3 . Only latest records. And the table dns_lookup_table has records that comes into it dynamically. Sometimes the url record can not be inserted if not available. So order is missing. So I think it is not possible with desc limit .

You can use a window function to get the latest row for each URL:

select *
from (
   select url, 
          update_time, 
          dns_time, 
          row_number() over (partition by url order by update_time desc) as rnk
   from dns_lookup_table
) as t
where rnk = 1

SQLFiddle example: http://sqlfiddle.com/#!12/fbd38/1


Edit

You can also use something like this:

select *
from dns_lookup_table lt
  join (
     select url, 
            max(update_time) as latest_time
     from dns_lookup_table
     group by url
  ) as mt on mt.latest_time = lt.update_time 
         and mt.url = lt.url;
SELECT *
 FROM dns_lookup_table lut
 WHERE NOT EXISTS (
   SELECT *
   FROM dns_lookup_table nx
   WHERE nx.url = lut.url
     AND nx.update_time > lut.update_time
   );  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM