1

这是我的桌子:

ID    Last_modified_date     status
1     06-01-2013 17:05       New
1     06-02-2013 12:08       Assigned
2     07-03-2013 18:17       New
2     08-03-2013 15:12       Assigned
2     08-03-2013 18:05       Fixed

我需要以下结果

ID    Last_modified_date     status       Trigger
1     06-01-2013 17:05       New          False
1     06-02-2013 12:08       Assigned     True
2     07-03-2013 18:17       New          False
2     08-03-2013 15:12       Assigned     False
2     08-03-2013 18:05       Fixed        True

我可以使用这个触发器来检索每个 ID 的最后记录。

4

1 回答 1

1

这个会给你想要的结果,但我不确定这是你想要的逻辑:

with cte as (
    select
        *,
        row_number() over(partition by id order by last_modified_date desc) as row_num
    from Table1
)
select
    id, last_modified_date,  status,
    case when row_num = 1 then 'True' else 'False' end as "Trigger"
from cte
order by id, last_modified_date asc

或者,如果您只想要每个 id 的最后一行,您可以使用distinct on

select distinct on (id)
    id, last_modified_date,  status
from Table1
order by id, last_modified_date desc

=> sql 小提琴演示

更新 如果您需要触发器,请尝试以下操作:

create or replace function tr_Table1_func()
returns trigger
as
$$
begin
    update Table1 as t set
        tr = t.last_modified_date > new.last_modified_date
    where t.id = new.id and t.tr = TRUE
    returning not tr into new.tr;

    new.tr = coalesce(new.tr, TRUE);

    return new;
end;
$$
language plpgsql;

create trigger tr_Table1
before insert on Table1
for each row execute procedure tr_Table1_func();

=> sql 小提琴演示

于 2013-09-05T17:14:15.973 回答