Dariel Pratama
Dariel Pratama

Reputation: 1675

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.

Upvotes: 0

Views: 178

Answers (2)

user330315
user330315

Reputation:

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

Upvotes: 1

Joe Love
Joe Love

Reputation: 5982

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

Upvotes: 0

Related Questions