0

我有以下递归查询,它将在 11g 中运行,但在 Oracle 10g 数据库中不受支持:

with st as (
    select
        rownum id,
        case  
            when rownum-1 < 1 then null
            else rownum-1
        end parent_id,
        customer, 
        tickets
    from tickets
),
st2(id, parent_id, customer, tickets, offset) as (
        select
            id, parent_id, shuffler_id, subno, contrno, tickets, 0 offset
        from st
        where id = 1
    union all
        select
            st2.id, st2.parent_id, st2.tickets, (st.tickets + st.offset) offset
        from st, st2
        where st2.parent_id = st.id
)
select * from st2

我要做的是根据前一行的列ticketsoffset(相同的计算列)计算每行的偏移量,并且我从偏移量为 0 的第一行开始;我需要依赖于在执行查询期间计算的列这一事实需要递归。

问题是 Oracle 10g 不支持上述查询,所以我尝试connect by改用哪个有效,但丑陋的部分是它的效率极低:

with st as (
    select
        rownum id,
        case  
            when rownum-1 < 1 then null
            else rownum-1
        end parent_id, 
        customer,
        tickets
    from tickets
)
select
    id, 
    parent_id,
    customer,
    tickets,
    (
        select nvl(sum(tickets), 0) from st
        where level <  x.id
        start with id = 1
        connect by prior id = parent_id
    ) offset
from st x

使用第二个查询,我将所有先前的行求和,这可以完成这项工作,但也是多余的,我不能依赖该表何时增长到数百万条记录。

关于如何在 Oracle 10g 数据库中实现类似于第一个查询的任何想法?

4

1 回答 1

3
  select 
    id, 
    customer,
    tickets,
    nvl(
      sum(tickets) over (
        order by id rows between unbounded preceding and 1 preceding
      ), 0) as offset
  from (    
    select
        rownum id,
        customer, 
        tickets
    from tickets
  )

甚至更短(不引入ids)

  select 
    customer,
    tickets,
    nvl(
      sum(tickets) over (
        order by rownum rows between unbounded preceding and 1 preceding
      ), 0) as offset
  from tickets
于 2013-03-13T11:24:14.950 回答