-2

我们有一个定价表,我需要获取每个季度的第一条实时记录,表结构是这样的:

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 上的第一条现场记录,如上图中突出显示的示例。

4

1 回答 1

1

您可以使用:

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

于 2021-03-23T14:40:41.280 回答