SQL选择最近日期的所有条目

SQL选择最近日期的所有条目,sql,postgresql,Sql,Postgresql,我在postgres db中有下表: create table aerialpic( id varchar(36) not null, version integer default 1 not null, filename varchar not null, location varchar not null, takenat bigint); 使用一些测试数据: INSERT INTO public.aerialpic (id, version, f

我在postgres db中有下表:

create table aerialpic(
    id varchar(36) not null,
    version integer default 1 not null,
    filename varchar not null,
    location varchar not null,
    takenat bigint);
使用一些测试数据:

INSERT INTO public.aerialpic (id, version, filename, location, takenat) VALUES ('f98c03b2-126d-4c0c-af84-645537a72f60', 1, 'South Passage Bar 1', 'South Passage', 1531720800000);
INSERT INTO public.aerialpic (id, version, filename, location, takenat) VALUES ('74b78410-e80c-42cd-a26d-321e9b121da3', 1, 'Jumpinpin Bar 1', 'Jumpinpin Bar', 1531721700000);
INSERT INTO public.aerialpic (id, version, filename, location, takenat) VALUES ('b73cc37c-cb33-473e-a421-885566b4a2f1', 1, 'Wide Bay Bar3 1', 'Wide Bay Bar', 1531630800000);
INSERT INTO public.aerialpic (id, version, filename, location, takenat) VALUES ('b73cc37c-cb33-473e-a421-885566b4a2f2', 1, 'Wide Bay Bar3 2', 'Wide Bay Bar', 1531631800000);
INSERT INTO public.aerialpic (id, version, filename, location, takenat) VALUES ('b73cc37c-cb33-473e-a421-885566b4a2f3', 1, 'Wide Bay Bar3 3', 'Wide Bay Bar', 1530631800000);
INSERT INTO public.aerialpic (id, version, filename, location, takenat) VALUES ('f98c03b2-126d-4c0c-af84-645537a72f61', 1, 'South Passage Bar 2', 'South Passage', 1530720800000);
对于每个唯一的
位置
最近的条目,我确实需要获得以下SQL:

select *
from (
    select *, row_number() 
    over (partition by location order by takenat desc) as row_number
    from aerialpic
) as rows
where row_number = 1
这很有效,但现在我需要将其更改为还返回每个唯一的
位置
最近的条目加上该位置与最近的条目在同一天的任何其他条目

使用测试数据的结果将返回包含以下内容的
filename
行:

South Passage Bar 1
Jumpinpin Bar 1
Wide Bay Bar3 1
Wide Bay Bar3 2

我想你只需要
rank()

如果
takenat
表示毫秒级Unix时间戳,则还需要一些算法:

select a.*
from (select a.*,
             rank() over (partition by location order by floor(takenat / (24*60*60*1000)) desc) as row_number
      from aerialpic a
     ) a
where row_number = 1;
select a.*
from (select a.*,
             rank() over (partition by location order by floor(takenat / (24*60*60*1000)) desc) as row_number
      from aerialpic a
     ) a
where row_number = 1;