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

标签 sql postgresql

我在 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/

相关文章:

sql - 如何为非生产环境获取 postgresql 数据库的部分转储?

sql - 在 Postgres 中将日期转换为一年中的某一天

SQL 幂等性

php - 使用 laravel eloquent 进行计算(类似总账)

c# - 难以理解 TransactionScope

ruby-on-rails - 在本地使用 sqlite3 在 Heroku 上设置 Rails 3.2.2 应用程序

sql-server - SQL Server 到 PostgreSQL - 迁移和设计问题

sql - Postgres 类似于 SQL Server 中的 CROSS APPLY

mysql - SQL - 替换 SELECT 子句中的值

sql - 返回基于 a 的条目包含带有 sql 的谓词