简体   繁体   English

在Oracle中按分组?

[英]Group by in Oracle?

I have the following table in 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

I'm trying to have this output 我正在尝试获得此输出

    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 goes with the FIRST occurrence of Start for each ID and 0 goes wit the LAST occurrence of End for each ID, individually separated by UNIT. 每个ID的ID首次出现“开始”,每个ID的“ 0”表示最后一个“ End”,由UNIT分别分隔。

@Egor Skriptunoff and @Gordon Linoff helped me build a query for the first and last occurrence of ID, but I wonder what we have to do to group the results by UNIT. @Egor Skriptunoff和@Gordon Linoff帮助我建立了ID的第一个和最后一个出现的查询,但是我想知道我们该怎么做才能按UNIT对结果进行分组。

Code that is already working not bringing the 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

I'm trying to add the extra column UNIT that comes from the same table. 我正在尝试添加来自同一表的额外列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

but it's not working :( 但它不起作用:(

Many thanks in advance! 提前谢谢了!

You can readily add unit to my version: 您可以随时将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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM