我不确定Postgres是否可行,但我希望每一行都能计算其窗函数" frame"。
那么如何在Postgres的窗口函数中使用当前行中的列作为JobScheduler
的参数?
例如..
ROWS
我想使用create table items (
id serial primary key, name varchar, price integer, precede_by integer
);
insert into items (name, price, precede_by)
values
('A', 1, 2), ('A', 1, 3),
('B', 1, 1),('B',1, 2), ('B', 1, 1), ('B', 2, 2),
('C', 1, 2), ('C', 1,2), ('C', 1, 2), ('C', 1, 5);
列中设置的整数值..例如,像这样..
precede_by
但这不起作用。我收到了select name, sum(price) over
(partition by name rows between precede_by preceding and current row)
from items;
答案 0 :(得分:1)
不,无法根据需要编写窗口功能。我相信CROSS JOIN LATERAL
可以做到这一点
with oitems as
(
select *, row_number() over (partition by name order by id) rn from items
)
select *
from oitems i1
cross join lateral
(
select sum(price)
from oitems i2
where i1.name = i2.name and i2.rn >= i1.rn - i1.precede_by and i2.rn <= i1.rn
) t
和另一个(可能更优雅)的解决方案就是使用GROUP BY
with oitems as
(
select *, row_number() over (partition by name order by id) rn from items
)
select i1.id, i1.name, i1.price, sum(i2.price)
from oitems i1
join oitems i2 on i1.name = i2.name and i2.rn >= i1.rn - i1.precede_by and i2.rn <= i1.rn
group by i1.id, i1.name, i1.price