简体   繁体   English

postgresql:表中给定id y的id x的最后一次出现值

[英]postgresql: last occurred value of id x for a given id y in a table

Hi I'm new to postgresql and need a little help. 嗨,我是Postgresql的新手,需要一点帮助。

i have the following table, where rows belong to class 1 or 2 based on the value of column pf. 我有下表,其中基于列pf的值,行属于1类或2类。 The rows are ordered by charttime. 这些行按charttime排序。

table

i want a new column called prev_val, and the prev_val corresponding row should be equal to the last occurring value of the the class diff from the corresponding rows class. 我想要一个称为prev_val的新列,并且prev_val对应的行应等于对应行类的diff类的最后出现的值。 ie ex- if pf=2 for a given row then the prev_val of this row must be equal to the previous value of a row with pf=1. 即,如果给定行的pf = 2,则该行的prev_val必须等于pf = 1的行的先前值。

ie

for a given pf=2, prev_val=valuenum of pf=1 with charrttime less than current row 对于给定的pf = 2,pf = 1的prev_val = valuenum,charrttime小于当前行

for a given pf=1, prev_val=valuenum of pf=2 with charrttime less than current row 对于给定的pf = 1,pfv = 2的prev_val = valuenum,charrttime小于当前行

You are looking for the function lag() . 您正在寻找lag()函数。 If I understand the question correctly: 如果我正确理解了这个问题:

select t.*,
       lag(valuenum) over (partition by pf order by charttime) as prev_val
from t;

EDIT: 编辑:

One way to express the logic would be: 表达逻辑的一种方法是:

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;

Unfortunately, Postgres does not yet support ignore nulls , so this doesn't work. 不幸的是,Postgres尚不支持ignore nulls ,因此这行不通。 The following might work: 以下可能有效:

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;

This uses the filter clause for the same (and more efficient) effect. 这将使用filter子句以达到相同(且效率更高)的效果。

An alternative that should definitely work (but not on large tables) is a lateral join or subquery: 横向连接或子查询肯定应该起作用(但不适用于大表):

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM