2015-10-16 99 views
0

我有一個表中的列獲得第一行與空

drop TABLE "public"."opportunities"; 
CREATE TABLE "public"."opportunities" ( 
    "itemcode"  VARCHAR COLLATE "default", 
    "creationtime" TIMESTAMPTZ(6) NOT NULL, 
    "finishtime" TIMESTAMPTZ(6), 
    "ordertag"  INT8, 
    "trackingblob" VARCHAR 
); 
insert into opportunities VALUES ('1', now(), null, NULL, 'blob1'); 
insert into opportunities VALUES ('1', now(), null, 2, 'blob2'); 
insert into opportunities VALUES ('1', now(), null, null, 'blob3'); 
insert into opportunities VALUES ('2', now(), null, NULL, 'blob1a'); 
insert into opportunities VALUES ('2', now(), null, 2, 'blob2a'); 
insert into opportunities VALUES ('2', now(), null, null, 'blob3a'); 

預期的結果將與blob1和blob1a行。

我想獲取每個orderTag,OrderTag的前一個條目的跟蹤blob爲null - 可能會有時間戳之後的行應該被忽略。 這是可能在一個單一的SQL或我需要用兩個步驟編寫程序?

+0

您可以添加一些樣本數據和預期結果(包含樣本數據)嗎? – jarlh

+0

我已經按要求添加了一個樣本。 – weismat

+0

如果blob3有一個OrderTag - 應該返回blob2還是blob1? – jarlh

回答

0
select * from opportunities op1 
where (select ordertag from opportunities op2 
     where op2.creationtime = 
      (select min(creationtime) from opportunities op3 
      where op3.creationtime > op1.creationtime)) is not null 

I.e.返回下一行的行(creationtime-wise)有一個非空的ordertag。

+0

與上面的sql語句一起運行時,我沒有返回任何行 - 我也錯過了按訂單標記分組。 – weismat

+0

當我測試它返回預期的行。也許時間差異?減慢插入,看看它是否有任何區別? – jarlh

+0

我會再試一次 – weismat