在我的Postgres 14数据库中,我有一个类似下面的表.
在我的SELECT
中,我想添加两列来显示last_contract_id
和next_contract_id
,如果它们存在的话.棘手的部分是,如果rental_start_date
在下面或上面的行上是相同的,我想跳过该行,直到它改变.所以在本例中,我希望807的last_contract_id
为空,而不是806,因为第一行的id为3,rental_start_date
发生了变化.
我试图添加这两行,但这并没有跳过具有相同rental_start_date
的同行:
lag(contract_id) over (partition by objekt_id order by id) as last_contract_id,
lead(contract_id) over (partition by objekt_id order by id) as next_contract_id
Schema:个
CREATE TABLE object_history (
objekt_id int4 NOT NULL,
id serial NOT NULL,
rental_start date NULL,
rental_end date NULL,
contract_id int4 NULL
);
INSERT INTO public.object_history
(objekt_id, id, rental_start, rental_end, contract_id)
VALUES(77920, 6, '2023-06-01', '2100-01-01', 807);
INSERT INTO public.object_history
(objekt_id, id, rental_start, rental_end, contract_id)
VALUES(77920, 5, '2023-06-01', '2100-01-01', 806);
INSERT INTO public.object_history
(objekt_id, id, rental_start, rental_end, contract_id)
VALUES(77920, 4, '2023-06-01', '2100-01-01', 803);
INSERT INTO public.object_history
(objekt_id, id, rental_start, rental_end, contract_id)
VALUES(77920, 3, '2023-05-01', '2023-05-31', NULL);
INSERT INTO public.object_history
(objekt_id, id, rental_start, rental_end, contract_id)
VALUES(77920, 2, '2022-01-01', '2023-04-30', 802);
INSERT INTO public.object_history
(objekt_id, id, rental_start, rental_end, contract_id)
VALUES(77920, 1, '2017-11-01', '2021-12-31', NULL);
Select * from object_history;
| objekt_id | id | rental_start | rental_end | contract_id |
| --------- | --- | ------------------------ | ------------------------ | ----------- |
| 77920 | 6 | 2023-06-01T00:00:00.000Z | 2100-01-01T00:00:00.000Z | 807 |
| 77920 | 5 | 2023-06-01T00:00:00.000Z | 2100-01-01T00:00:00.000Z | 806 |
| 77920 | 4 | 2023-06-01T00:00:00.000Z | 2100-01-01T00:00:00.000Z | 803 |
| 77920 | 3 | 2023-05-01T00:00:00.000Z | 2023-05-31T00:00:00.000Z | |
| 77920 | 2 | 2022-01-01T00:00:00.000Z | 2023-04-30T00:00:00.000Z | 802 |
| 77920 | 1 | 2017-11-01T00:00:00.000Z | 2021-12-31T00:00:00.000Z | |