根据列值获取最大日期

get max date based on column value

假设我有以下 table 命名为 image_play 并且有以下行和列

+-------------------------------------------+
|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  |
+-------------------------------------------+

从那个 table 我想 select MAX 每个 image_category 约会。所以结果是

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

我已经尝试过对每个类别进行查询,如下所示:

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

但它不起作用。请帮助我..非常感谢。

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

Postgres 特定且速度最快的解决方案是使用 distinct on:

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

经常使用 window 函数也比在派生 table 上使用自连接更快(这是标准 SQL,不是 Postgres 特定的)。

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