[英]SQL: Identify first and last date within each consecutive group of days
Objective:客观的:
The objective is to find the first and last observation date for which the room has a constant price using postgresql SQL queries.目标是使用 postgresql SQL 查询找到房间价格不变的第一个和最后一个观察日期。
We are completely lost so any guidance would be highly appreciated.我们完全迷失了所以任何指导将不胜感激。
Create example:创建示例:
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 data:插入数据:
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')
Expected outcome:预期结果:
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
This is a gap & island problem -you can try using row_number()
这是一个间隙和岛屿问题 - 您可以尝试使用row_number()
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
OUTPUT:输出:
room_id check_in first_observation last_observation price
1 01/05/2019 00:00:00 01/01/2019 00:00:00 03/01/2019 00:00:00 100
1 01/05/2019 00:00:00 04/01/2019 00:00:00 07/01/2019 00:00:00 150
1 01/05/2019 00:00:00 08/01/2019 00:00:00 09/01/2019 00:00:00 100
2 01/05/2019 00:00:00 01/01/2019 00:00:00 09/01/2019 00:00:00 200
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.