可以在Oracle的查询中两次引用CTE吗?

时间:2011-07-14 01:07:31

标签: oracle common-table-expression

我有一系列CTE,最后我想从最后一次选择两次。 Oracle允许我做任何一个选择但不是两者的联合(即使我做“select * from(select union select)”。我唯一可以缩小问题的是指两个中的“runinfo”选择,但这本身并不像香农所显示的那样。

WITH lastTen AS (
SELECT id
FROM (SELECT autobuild_id,  id, rank() OVER (PARTITION BY autobuild_id ORDER BY id DESC) as rank
      FROM runs
      WHERE status='FINISHED' AND type='FULL' AND build_failed in ('n', 'N'))
WHERE rank <= 10
),

recentAvg AS (
SELECT autobuild_id, avg(elapsed) avgtime
FROM runs
JOIN lastTen ON (runs.id = lastTen.id)
GROUP BY autobuild_id
),

runinfo AS (
SELECT autobuildid, runid, changelist, status, age
FROM (
    SELECT runs.autobuild_id autobuildid, runs.id runid, changelist, runs.status status, runs.create_date, a.avgtime,
       CASE WHEN status = 'RUNNING' THEN TO_NUMBER(sysdate - start_date)*86400 -- in seconds to compare to elapsed
            WHEN status = 'TO BE' THEN TO_NUMBER(sysdate - create_date) -- in days
       END AS age
    FROM runs
    LEFT JOIN recentAvg a ON (runs.autobuild_id = a.autobuild_id)
    )
WHERE (status = 'RUNNING' AND age > avgtime * 1.5)
   OR (status = 'TO BE' AND age > 1)
ORDER BY autobuildid, runid DESC
),

running AS (
SELECT autobuilds.id, name, runid, changelist, runinfo.status, age
FROM runinfo
JOIN autobuilds ON (runinfo.autobuildId=autobuilds.id)
WHERE runinfo.status='RUNNING'
),

tobe AS (
SELECT autobuildid, name, runid, changelist, status, age
FROM (SELECT autobuildid, name, runid, changelist, runinfo.status, age, RANK() OVER (PARTITION BY autobuildid ORDER BY runid DESC) AS rank
     FROM runinfo
     JOIN autobuilds ON (runinfo.autobuildid=autobuilds.id)
     WHERE runinfo.status='TO BE')
WHERE rank=1
)

SELECT * FROM running
UNION ALL
SELECT * FROM tobe

1 个答案:

答案 0 :(得分:9)

什么是最简单的查询对您不起作用?

什么是完整的错误消息?

Oracle允许CTE被引用两次,但我不明白你在尝试什么:

SQL> with a as (select * from dual)
  2     , b as (select * from a)
  3     , c as (select * from b)
  4  select *
  5  from b, c
  6  where b.dummy = c.dummy;

D D
- -
X X