2

可以使用哪种 Oracle SQL 技术来连接这些行:

id | from | to
--------------
 a |   20 | 25
 a |   26 | 30
 a |   32 | 40
 b |    1 |  5
 b |    7 | 10
 b |   11 | 20

对于这样的结果:

 a |   20 | 30
 a |   32 | 40
 b |    1 |  5
 b |    7 | 20

? 假设fromand是一个整数周期的开始和结束,并且有必要为'sto选择一个非中断周期id

只是寻找正确的方向和例子,这可以使用group byorconnect by或其他东西来完成吗?

数据库是Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production

4

3 回答 3

1

也许类似的东西:

select
    field_id,
    min(field_from),
    max(field_to)
from (
    select
        field_from,
        field_to,
        field_id,
        sum(willSum) over(partition by field_id order by field_from) as GID
    from (
        select
            field_from,
            field_to,
            field_id,
            case when field_from
                    = Lag(field_to) over(partition by field_id order by field_from)
                 then 0 else 1 end as willSum + 1
        from
            rj_mytest
        )
    )
group by
    field_id,
    GID
order by
    field_id,
    min(field_from);

有几个类似的例子:https ://forums.oracle.com/thread/969005

于 2013-10-07T17:49:52.130 回答
1
select id, max("from") as "from", max("to") as "to"
from (
  select 
    nvl(prv.id, nxt.id) id,
    nxt."from", 
    prv."to", 
    nvl2(nxt."to", 
      row_number() over (partition by nxt.id order by nxt."from"), 
      row_number() over (partition by prv.id order by prv."to")) rn
  from t prv full join t nxt on
    prv.id = nxt.id and prv."to" + 1 = nxt."from"
  where nxt."to" + prv."to" is null 
)
group by id, rn

小提琴

于 2013-10-07T18:03:37.663 回答
1

另一种方法,它使用model子句将组号分配给连续的值对:

select id1
     , min(from1) as from1
     , max(to1)   as to1
  from (select *
          from t1
          model
          partition by (id1)
          dimension by (row_number() over(partition by id1 order by from1) as rn)
          measures(from1, to1, 1 as grp)
          rules(
              grp[rn] = case
                          when from1[cv()] = nvl(to1[cv()-1] + 1, from1[cv()]) 
                          then nvl(grp[cv() - 1], 1)
                          else grp[cv() - 1] + 1
                        end 
               )
)
group by id1
       , grp
order by id1
       , from1

结果:

ID1      FROM1        TO1
--- ---------- ----------
a           20         30 
a           32         40 
b            1          5 
b            7         20

SQLFiddle 演示

于 2013-10-07T18:13:37.763 回答