在我的数据库中,我有各种带有主键、开始日期和结束日期的表
我正在尝试创建一个视图表来连接其中一些周期,以便我可以将该表发送到 PowerBI 并使用它。
我的问题是这些表有许多不同的形状,所以我使用生成系列方法来扩展它,然后将其他表与我想要的列连接到主表。
我无法将此表重新组合回 start_date 和 end_date 格式。因为有些表留下空值,即使它们跳过一些日期,它们最终也会分组在一起:
例如:
| id_employe | id_function | date
-
| 1 | null | 1
| 1 | null | 2
| 1 | 3 | 3
| 1 | 3 | 4
| 1 | 3 | 5
| 1 | null | 6
| 1 | null | 7
我如何有效地将这些分组为:
| id_employe | id_function | start_date | end_date
| 1 | null | 1 | 2
| 1 | 3 | 3 | 4
| 1 | null | 5 | 7
如果我有 6 个不同的列在查询中创建空值,我该如何执行此操作?
在generate_series之后我可以使用什么方法来重新分组,以正确计算开始和结束日期?
您可以使用窗口函数识别分组,然后将分组编号(在我的示例中为
island
)添加到group by
列中:
with deltas as (
select *,
(id_function is distinct from lag(id_function) over w)::int as delta
from intab
window w as (partition by id_employe order by ddate)
), islands as (
select *, sum(delta) over w as island
from deltas
window w as (partition by id_employe order by ddate)
)
select id_employe, id_function, min(ddate) as start_date, max(ddate) as end_date
from islands
group by id_employe, island, id_function
order by start_date;