延迟函数在Postgresql的多行



我有一个这样的表

b.b_id fp.fp_id b.name
1      10       Dan
1
1
1
2      15       Michelle
2
3      20       Steve
3
3

我试图得到这个输出

b.b_id fp.fp_id b.name
1      10       Dan
1               Dan
1               Dan
1               Dan
2      15       Michelle
2               Michelle
3      20       Steve
3               Steve
3               Steve

我的想法是使用滞后函数,但有了这个代码,我只能填写下面的1行。

select b.b_id,fp.fp_id,
case 
when fp.fp_id is null then lag(b.name,1) over (partition by b.b_id order by b.b_id,fp.fp_id) 
else b.name 
end as name 
from  b 
left join  fp on fp.id = b.fp_id

当前输出

b.b_id fp.fp_id b.name
1      10       Dan
1               Dan
1
1
2      15       Michelle
2               Michelle
3      20       Steve
3               Steve
3

有没有简单的方法来解决这个问题?

CREATE temp TABLE test101 (
id bigint,
fp_id bigint,
name text
);
INSERT INTO test101
VALUES (1, 10, 'dan'),
(1, NULL, NULL),
(1, NULL, NULL),
(1, NULL, NULL),
(2, 15, 'Michelle'),
(2, NULL, NULL),
(3, 20, 'Steve'),
(3, NULL, NULL),
(3, NULL, NULL);
SELECT
id,
fp_id,
first_value(name) OVER (PARTITION BY id ORDER BY id ASC nulls LAST, fp_id NULLS LAST)
FROM
test101;

最新更新