我在 postgres 数据库中有下表:
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 来为每个唯一的 location
获取最新的条目:
select *
from (
select *, row_number()
over (partition by location order by takenat desc) as row_number
from aerialpic
) as rows
where row_number = 1
这很有效,但现在我需要更改它,以便还为每个唯一的 location
返回最近的条目 plus 该位置位于同一位置的任何其他条目一天作为最近的一天。
使用测试数据的结果将返回包含 filename
的行:
South Passage Bar 1
Jumpinpin Bar 1
Wide Bay Bar3 1
Wide Bay Bar3 2
最佳答案
我认为你只需要rank()
:
select a.*
from (select a.*,
rank() over (partition by location order by takenat desc) as row_number
from aerialpic a
) a
where row_number = 1;
如果 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;
关于SQL选择最近日期的所有条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57838181/