简体   繁体   中英

get max date based on column value

Assume I have the following table named image_play and have the following rows & cols

+-------------------------------------------+
|image_name | image_category  | image_date  |
+-------------------------------------------+
|a.jpg      | WSA             | 2015-02-10  |
|b.jpg      | WSP             | 2015-02-09  |
|c.jpg      | GSST            | 2015-02-09  |
|d.jpg      | WSA             | 2015-02-09  |
|e.jpg      | GSST            | 2015-02-08  |
|f.jpg      | WSP             | 2015-02-08  |
+-------------------------------------------+

From that table I want to select MAX date for each image_category . so the result would be

a.jpg      | WSA             | 2015-02-10
b.jpg      | WSP             | 2015-02-09
c.jpg      | GSST            | 2015-02-09

What I already try is making a query for each category like so:

SELECT * FROM image_play t JOIN (SELECT MAX(image_date) AS MAXDATE FROM image_play WHERE image_category='GSST')t2 ON t.image_date=t2.MAXDATE

But it's not working. please help me..thanks a lot.

A Postgres specific and most much faster solution is to use distinct on :

select distinct on (image_category) image_name, image_category, image_date 
from image_play
order by image_category, image_date DESC

Very often using a window function is also faster than using a self-join on a derived table (this is standard SQL, not Postgres specific).

select image_name, image_category, image_date 
from (
  select image_name, image_category, image_date, 
         row_number() over (partition by image_category order by image_date desc) as rn
) t
where rn = 1
order by image_category
select ipl.*
from
(select max(ip.image_date) max_date, ip.image_category from image_play ip
group by ip.image_category) ipx
join image_play ipl on ipl.image_category=ipx.image_category
 and ipl.image_date=ipx.max_date

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