Oracle 10g递归查询 [英] Oracle 10g Recursive Query

查看:121
本文介绍了Oracle 10g递归查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following recursive query which would run in 11g but is not supported in Oracle 10g database:

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开始第一行;我需要依赖于查询执行期间正在计算的列这一事实需要递归.

What I'm trying to do is to calculate an offset for each row based on its previous row columns tickets and offset (same calculated column), and I'm starting the first row with an offset of 0; the fact that I need to depend on a column that I'm calculating during the execution of the query requires recursion.

问题是上面的查询在Oracle 10g中不受支持,因此我尝试使用connect by代替,但这很丑陋,因为它效率极低:

The issue is the above query is not supported in Oracle 10g, so I tried to use connect by instead which works, but the ugly part is it's extremely inefficient:

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

使用第二个查询,我对前面的所有行进行求和,这可以完成工作,但也很多余,我不能依赖于该表何时增长到数百万个记录.

Using the 2nd query I'm summing all the previous rows, which does the job but is redundant as well and I cannot depend on when this table grows to millions of records.

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

Any idea on how to implement something similar to the first query in Oracle 10g database?

推荐答案

  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
  )

或更短(不引入id s)

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

这篇关于Oracle 10g递归查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆