Postgresql有状态查询

时间:2017-11-09 08:10:23

标签: sql postgresql-9.5

鉴于下表:

CREATE TABLE "public"."x" 
(
   "id_user" int4, 
   "start_" timestamp(6),
   "end_" timestamp(6), 
   "olddir" int2, 
   "oldt" int4 
);

我需要使用以下伪逻辑描述的结果:

set state:=0; 
select id_user, start_, end_, state, 
       case 
         when olddir=0 and oldt=0 then state:=0; return state 
         when olddir=1 and oldt=1 then state:=1; return state 
         else return state 
       end;

经过大量阅读和测试后,我找不到基于RDB查询的答案。

编辑: select查询必须按时间戳排序,例如start_字段。并且每行的状态必须与上一行相同,直到满足某个条件(olddir = 0和oldt = 0:0;或; olddir = 1和oldt = 1:1)

1 个答案:

答案 0 :(得分:0)

尝试此查询 -

SELECT id_user
      ,start_
      ,end_
      ,CASE(WHEN olddir=0 and oldt=0 THEN 0
            WHEN olddir=1 and oldt=1 THEN 1 
            END) AS state
FROM YOUR_TABLE