PostgreSQL中多行的滞后功能

发布于 2025-02-11 22:20:20 字数 895 浏览 3 评论 0原文

我有一个像这样的表

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

是否有一些简单的方法可以解决此问题?

I have a table like this

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

Im trying to get this output

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

My idea was using the lag function but with this code i am only able to fill 1 row below.

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

Output at the moment

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

Is there some easy way to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灵芸 2025-02-18 22:20:20
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;
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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文