2015-10-16 117 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