最后一次出现在Oracle中

时间:2014-01-26 13:23:26

标签: sql database oracle

我在Oracle中有以下表格:

ID            Start                  End
AAAAA   20/08/1999 22:12    21/08/1999 00:50
AAAAA   20/08/1999 23:40    21/08/1999 00:51
BBBBB   20/08/1999 20:40    21/08/1999 00:53
AAAAA   21/08/1999 00:51    21/08/1999 01:16
AAAAA   21/08/1999 00:50    21/08/1999 01:20
BBBBB   20/08/1999 21:42    22/08/1999 00:53

我正在尝试输出

VALUE   TIMESTAMP
AAAAA   20/08/1999 22:12
0       21/08/1999 01:20
BBBBB   20/08/1999 20:40
0       22/08/1999 00:53

ID与每个ID的第一次出现Start相关,而0表示每个ID的最后一次出现End。

我第一次使用rownum = 1,但我找不到选择LAST事件的方法。我尝试使用COUNT(*),但效果不佳。任何人都可以帮助我吗?

到目前为止

代码:

--FIRST ROW ONLY
    select a.Start TIMESTAMP,
           a.ID VALUE
      from MyTable a
     WHERE rownum = 1
--END FIRST COLUMN
     union all 
--LAST ROW COLUMN

    select a.End TIMESTAMP,
           '0' VALUE
      from MyTable a
       --where ??????? 

非常感谢提前!

2 个答案:

答案 0 :(得分:1)

select VALUE, TIMESTAMP
from (
    select min(a.Start) TIMESTAMP,
           a.ID VALUE,
           a.ID,
           1 ORD
      from MyTable a
      group by a.ID

     union all 

    select max(a.End) TIMESTAMP,
           '0' VALUE,
           a.ID,
           2 ORD
      from MyTable a
      group by a.ID
)
order by ID, ORD

答案 1 :(得分:1)

这是一个奇怪的输出。您可以使用分析函数来获取它:

select (case when seqnum = 1 then id else '0' end) as id,
       (case when seqnum = 1 then start else "end" end) as timestamp
from (select t.*,
             row_number() over (partition by id order by start) as seqnum,
             count(*) over (partition by id) as cnt
      from table t
     ) t
where seqnum = 1 or seqnum = cnt;