SQL:确定每个连续组天内的第一个和最后一个日期

问题描述 投票:2回答:1

目的:

目标是使用postgresql SQL查询找到房间具有不变价格的第一个和最后一个观察日期。

我们完全迷失了,所以任何指导都会受到高度赞赏。

创建示例:

CREATE TABLE table_prices
(
    pk int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    room_id character varying(50) COLLATE pg_catalog."default",
    check_in date,
    price integer,
    observation_date date
)

插入数据:

insert into table_prices (room_id, check_in, price, observation_date) values
('1', '2019-05-01', 100, '2019-01-01'),
('1', '2019-05-01', 100, '2019-01-02'),
('1', '2019-05-01', 100, '2019-01-03'),
('1', '2019-05-01', 150, '2019-01-04'),
('1', '2019-05-01', 150, '2019-01-05'),
('1', '2019-05-01', 150, '2019-01-06'),
('1', '2019-05-01', 150, '2019-01-07'),
('1', '2019-05-01', 100, '2019-01-08'),
('1', '2019-05-01', 100, '2019-01-09'),
('2', '2019-05-01', 200, '2019-01-01'),
('2', '2019-05-01', 200, '2019-01-02'),
('2', '2019-05-01', 200, '2019-01-03'),
('2', '2019-05-01', 200, '2019-01-04'),
('2', '2019-05-01', 200, '2019-01-05'),
('2', '2019-05-01', 200, '2019-01-06'),
('2', '2019-05-01', 200, '2019-01-07'),
('2', '2019-05-01', 200, '2019-01-08'),
('2', '2019-05-01', 200, '2019-01-09')

预期结果:

    room_id, check_in, first_observation, last_observation, price
1, 2019-05-01, 2019-01-01, 2019-01-03, 100
1, 2019-05-01, 2019-01-04, 2019-01-07, 150
1, 2019-05-01, 2019-01-08, 2019-01-09, 100
2, 2019-05-01, 2019-01-01, 2019-01-09, 200
sql postgresql window gaps-and-islands
1个回答
2
投票

这是一个差距和岛屿问题 - 你可以尝试使用qazxsw poi

row_number()

DEMO

OUTPUT:

select room_id, check_in,min(observation_date) first_observation,max(observation_date)
last_observation,price
from
(
select *,island=row_number() over(partition by room_id order by observation_date) - 
row_number() over(partition by room_id, price order by observation_date) 
from table_prices
)A group by room_id, check_in,island,price
© www.soinside.com 2019 - 2024. All rights reserved.