Oracle SQL查询结果到临时表中以供在子查询中使用

时间:2015-05-14 04:19:25

标签: sql oracle temp-tables

我想创建一个临时表,该表是从一个查询派生而来,用于另一个子查询,以便按条件简化rownum()和分区。我输入的查询如下所示,但它返回错误t.trlr_num无效标识符。

with t as
(select distinct
          ym.trlr_num,
           ym.arrdte,
           ri.invnum,
           ri.supnum
from rcvinv ri, yms_ymr ym
where ym.trlr_cod='RCV'
and ri.trknum = ym.trlr_num
and ym.wh_id <=50
and ym.trlr_stat in ('C','CI','R','OR')
and ym.arrdte is not null
order by ym.arrdte desc
)
select trlr_number, invnum, supnum
from
(
  select 
    t.trlr_num, t.invnum, t.supnum,
    row_number() over (partition by t.trlr_number,t.invnum order by t.arrdte) as rn 
  from t
)
where rn = 1; 

从上面,我提出了一个条件来创建一个表t作为临时表,用于下面的select语句。但似乎是错误输出无效的标识符。

2 个答案:

答案 0 :(得分:0)

似乎是拼写错误,用trlr_num替换trlr_number并且它可以正常工作

with t as
(select distinct
          ym.trlr_num,
           ym.arrdte,
           ri.invnum,
           ri.supnum
from rcvinv ri, yms_ymr ym
where ym.trlr_cod='RCV'
and ri.trknum = ym.trlr_num
and ym.wh_id <=50
and ym.trlr_stat in ('C','CI','R','OR')
and ym.arrdte is not null
order by ym.arrdte desc
)
select trlr_num, invnum, supnum
from
(
  select 
    t.trlr_num, t.invnum, t.supnum,
    row_number() over (partition by t.trlr_num,t.invnum order by t.arrdte) as rn 
  from t
)
where rn = 1; 

答案 1 :(得分:0)

您可以将 WITH子句中的多个子查询用作单独的临时表。这将很容易理解:

WITH t AS
  (SELECT DISTINCT ym.trlr_num trlr_num,
    ym.arrdte arrdte,
    ri.invnum invnum,
    ri.supnum supnum
  FROM rcvinv ri,
    yms_ymr ym
  WHERE ym.trlr_cod ='RCV'
  AND ri.trknum     = ym.trlr_num
  AND ym.wh_id     <=50
  AND ym.trlr_stat IN ('C','CI','R','OR')
  AND ym.arrdte    IS NOT NULL
  ),
  t1 AS (
  SELECT t.trlr_num,
  t.arrdte,
  t.invnum,
  t.supnum,
  row_number() OVER (PARTITION BY t.trlr_num, t.invnum ORDER BY t.trlr_num, t.invnum DESC) rn
  FROM t
  )
SELECT trlr_num, arrdte, invnum, supnum 
   FROM t1 
  WHERE rn = 1;