我有一些分析数据,其中访问者的单个活动流是我们的网站,在跟踪的一部分中,有一个ID,以后的标识符是一个不同的值。如何使用SQL填充数据以使其完整。
id1 | id2 | timestamp
-----+-----+---------------------
null | 3 | 123450
null | 3 | 123451
null | 3 | 123452
5 | 3 | 123453
5 | 3 | 123454
5 |null | 123455
5 |null | 123456
5 |null | 123457
...
null | 8 | 123450
null | 8 | 123451
null | 8 | 123452
9 | 8 | 123453
9 | 8 | 123454
9 |null | 123455
9 |null | 123456
9 |null | 123457
...
上面的两个部分是同一组的一部分,我知道这是因为它们本质上是停止记录id2的。
我想要一个查询或sql和中间表,这将使我能够填充上面的空值,以便拥有:
id1 | id2 | timestamp
-----+-----+---------------------
5 | 3 | 123450
5 | 3 | 123451
5 | 3 | 123452
5 | 3 | 123453
5 | 3 | 123454
5 | 3 | 123455
5 | 3 | 123456
5 | 3 | 123457
...
9 | 8 | 123450
9 | 8 | 123451
9 | 8 | 123452
9 | 8 | 123453
9 | 8 | 123454
9 | 8 | 123455
9 | 8 | 123456
9 | 8 | 123457
...
假设除了空值之外,还有一个id2
对应于一个id1
仅一个id1
对应一个id2
,除了null
select a.id1, a.id2, b.timestamp
from (
select min(id1) id1, id2
from tbl
where id1 is not null and id2 is not null
group by id2
) a right join tbl b
on (a.id1 = b.id1) OR (a.id2 = b.id2)
如果我们假设id1
和id2
出现在唯一的对中[[并且每个id永远都没有其他值,那么您可以简单地使用窗口函数:
select coalesce(id1, max(id1) over (partition by id2)) as id1,
coalesce(id2, max(id2) over (partition by id1)) as id2,
timestamp
from t;
没有这个假设,这个问题的格式就不好,没有具体的答案。Here是db <>小提琴