postgresql 获取每个季度的第一个实时记录

fcg9iug3  于 2023-01-30  发布在  PostgreSQL
关注(0)|答案(1)|浏览(144)

我们有一个定价表,我需要获得每个季度的第一条实时记录,该表的结构如下:

record_id (int)
start_date (date)
price (decimal)
live (boolean)

我需要能够获得每个季度的第一个"实时"记录。
到目前为止,我已经能够做到这一点:

SELECT DISTINCT EXTRACT(QUARTER FROM start_date::TIMESTAMP) as quarter,
EXTRACT(YEAR FROM start_date::TIMESTAMP) as year,
distinct start_date,
live
FROM record_pricing rp
group by year, quarter,record_instance_uid
order by year,quarter;

我得到这个:

如您所见,结果中有实时记录和非实时记录,我只需要每个Q上的第一条实时记录,如上图中突出显示的示例。

k5ifujac

k5ifujac1#

您可以用途:

SELECT *, ROW_NUMBER() OVER(PARTITION BY  year,quarter order by start_date asc) as Rank,
FROM (
SELECT  EXTRACT(QUARTER FROM start_date::TIMESTAMP) as quarter,
EXTRACT(YEAR FROM start_date::TIMESTAMP) as year,
record_instance_uid,live,start_date

FROM record_pricing rp
)Tab
where tab.Rank=1

相关问题