嗨,我是postgresql的新手,需要一些帮助。
我有下表,其中行根据列pf的值属于类1或2。行按charttime排序。
我想要一个名为prev_val的新列,并且prev_val对应的行应该等于来自相应行类的类diff的最后一个出现值。即,如果给定行的pf = 2,则该行的prev_val必须等于pf = 1的行的先前值。
即。
对于给定的pf = 2,prev_val = pf = 1的值,其中charrttime小于当前行
对于给定的pf = 1,prev_val = pf = 2的值,其中charrttime小于当前行
答案 0 :(得分:0)
您正在寻找功能lag()
。如果我正确理解了这个问题:
select t.*,
lag(valuenum) over (partition by pf order by charttime) as prev_val
from t;
编辑:
表达逻辑的一种方法是:
select t.*,
(case when pf = 1
then lag(case when pf = 2 then valuenum end ignore nulls) over (partition by pf order by charttime)
then lag(case when pf = 1 then valuenum end ignore nulls) over (partition by pf order by charttime)
end) as prev_other_val
from t;
不幸的是,Postgres还不支持ignore nulls
,所以这不起作用。以下可能有效:
select t.*,
(case when pf = 1
then lag(valuenum) filter (where pf = 2) over (partition by pf order by charttime)
then lag(valuenum) filter (where pf = 1) over (partition by pf order by charttime)
end) as prev_other_val
from t;
这使用filter
子句获得相同(且更有效)的效果。
一个绝对可行的替代方法(但不适用于大型表)是横向连接或子查询:
select t.*,
(select t2.valuenum
from t t2
where t2.pf <> t.pf and t2.chartime < t.chartime
order by t2.chartime desc
fetch first 1 row only
) as prev_other_val
from t;