在Oracle中分组?

时间:2014-01-26 16:39:14

标签: sql oracle

我在Oracle中有以下表格:

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

我正在尝试输出

    VALUE   TIMESTAMP            UNIT
    AAAAA   20/08/1999 22:12    Unit1
     0      21/08/1999 01:16    Unit1
    BBBBB   20/08/1999 20:40    Unit1
       0    22/08/1999 00:53    Unit1
    AAAAA   20/08/1999 23:40    Unit2
       0    21/08/1999 01:20    Unit2

ID与每个ID的第一次出现Start相关,0为每个ID的最后一次End出现,单独用UNIT分隔。

@Egor Skriptunoff和@Gordon Linoff帮助我构建了第一次和最后一次出现ID的查询,但我想知道我们要做什么来对UNIT分组结果。

已经无法携带UNIT的代码:

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

我正在尝试添加来自同一个表的额外列UNIT。

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

     union all 

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

但它不起作用:(

非常感谢提前!

1 个答案:

答案 0 :(得分:1)

您可以随时将unit添加到我的版本中:

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