PostgreSQL 函数可迭代/作用于具有状态的多行

2024-04-25

我有一个数据库,其中的列如下所示:

session | order | atype | amt
--------+-------+-------+-----
1       |  0    | ADD   | 10
1       |  1    | ADD   | 20
1       |  2    | SET   | 35
1       |  3    | ADD   | 10
2       |  0    | SET   | 30
2       |  1    | ADD   | 20
2       |  2    | SET   | 55

它代表正在发生的动作。每个会话从 0 开始。ADD 添加一个金额,而 SET 则设置该金额。我想要一个函数返回会话的最终值,例如

SELECT session_val(1); --returns 45
SELECT session_val(2); --returns 55

是否可以编写这样的函数/查询?我不知道如何用 SQL 做任何类似迭代的事情,或者是否可能。


嗯,这并不漂亮,但很实用:

select sum(amt) as session_val
from (
  select segment,
         max(segment) over() as max_segment,
         amt
  from (
    select sum(case when atype = 'SET' then 1 else 0 end)
               over(order by "order") as segment,
           amt
    from command
    where session = 2
  ) x
) x
where segment = max_segment

不过,在 PL/pgsql 中这非常简单:

create function session_val(session int) returns int stable strict
language plpgsql as $$
declare
  value int := 0;
  rec command%rowtype;
begin
  for rec in select * from command where command.session = session_val.session loop
    if rec.atype = 'SET' then
      value := rec.amt;
    elsif rec.atype = 'ADD' then
      value := value + rec.amt;
    end if;
  end loop;
  return value;
end $$;

所以我想,你自己选择吧。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PostgreSQL 函数可迭代/作用于具有状态的多行 的相关文章

随机推荐