PostgreSQL 在滞后函数后为缺失的单元格添加特定值
PostgreSQL adding specific value to missing cells after lag function
如果我运行查询:
SELECT status,
created_at,
lead(created_at) over(partition BY id
ORDER BY updated_at) ended_at
FROM salesdb.orders
我得到以下结果:
| status | created_at | ended_at |
| Opened | 2019-11-12 11:46:11 | 2019-11-15 12:04:13 |
| Pending | 2019-11-15 12:04:13 | 2019-11-19 23:03:24 |
| Completed | 2019-11-19 23:03:24 | |
| Opened | 2019-11-14 11:46:11 | 2019-11-17 12:04:13 |
| Pending | 2019-11-17 12:04:13 | 2019-11-20 23:03:24 |
| Completed | 2019-11-20 23:03:24 | |
我想在缺失的单元格中插入一个特定的结束日期,如 '2019-12-31'
像这样:
| status | created_at | ended_at |
| Opened | 2019-11-12 11:46:11 | 2019-11-15 12:04:13 |
| Pending | 2019-11-15 12:04:13 | 2019-11-19 23:03:24 |
| Completed | 2019-11-19 23:03:24 | 2019-12-31 00:00:00 |
| Opened | 2019-11-14 11:46:11 | 2019-11-17 12:04:13 |
| Pending | 2019-11-17 12:04:13 | 2019-11-20 23:03:24 |
| Completed | 2019-11-20 23:03:24 | 2019-12-31 00:00:00 |
使用lead()
的三参数形式:
SELECT status,
created_at,
lead(created_at, 1, '2019-12-31') over (partition BY id
order by updated_at
) as ended_at
FROM salesdb.orders
你也可以使用coalesce
:
select status,
created_at,
coalesce(
lead(created_at) over(partition by id order by updated_at),
'2019-12-31') ended_at
from salesdb.orders
如果我运行查询:
SELECT status,
created_at,
lead(created_at) over(partition BY id
ORDER BY updated_at) ended_at
FROM salesdb.orders
我得到以下结果:
| status | created_at | ended_at |
| Opened | 2019-11-12 11:46:11 | 2019-11-15 12:04:13 |
| Pending | 2019-11-15 12:04:13 | 2019-11-19 23:03:24 |
| Completed | 2019-11-19 23:03:24 | |
| Opened | 2019-11-14 11:46:11 | 2019-11-17 12:04:13 |
| Pending | 2019-11-17 12:04:13 | 2019-11-20 23:03:24 |
| Completed | 2019-11-20 23:03:24 | |
我想在缺失的单元格中插入一个特定的结束日期,如 '2019-12-31'
像这样:
| status | created_at | ended_at |
| Opened | 2019-11-12 11:46:11 | 2019-11-15 12:04:13 |
| Pending | 2019-11-15 12:04:13 | 2019-11-19 23:03:24 |
| Completed | 2019-11-19 23:03:24 | 2019-12-31 00:00:00 |
| Opened | 2019-11-14 11:46:11 | 2019-11-17 12:04:13 |
| Pending | 2019-11-17 12:04:13 | 2019-11-20 23:03:24 |
| Completed | 2019-11-20 23:03:24 | 2019-12-31 00:00:00 |
使用lead()
的三参数形式:
SELECT status,
created_at,
lead(created_at, 1, '2019-12-31') over (partition BY id
order by updated_at
) as ended_at
FROM salesdb.orders
你也可以使用coalesce
:
select status,
created_at,
coalesce(
lead(created_at) over(partition by id order by updated_at),
'2019-12-31') ended_at
from salesdb.orders