oracle:使用外部查询加入子查询

时间:2013-02-26 21:48:07

标签: oracle subquery

我有两个关于union的查询,如下所示:

     select   '00/00/0000' as payment_date , h1.customer_no
     from payments h1
     where not exists ( select 1 from payments h2 where h2.customer_no = h1.customer_no and h2.ctype = 'CASH' ) 
     and  h1.customer_no = 400
     group by h1.customer_no

     union

     select to_char(h1.payment_date, 'MM/DD/YYYY') , h1.customer_no
      from payments h1 inner   join ( select customer_no, max(payment_date ) as max_date from payments where ctype = 'CASH'  group by customer_no ) subQ
     on  ( h1.customer_no = subQ.customer_no
           and h1.payment_date = subQ.max_date   ) 
           and  h1.customer_no = 400
     group by h1.payment_date, h1.customer_no 

现在,我想在另一个查询中使用此联合。

  select * from (

    select   '00/00/0000' as payment_date , h1.customer_no
    from payments h1
    where not exists ( select 1 from payments h2 where h2.customer_no = h1.customer_no and h2.ctype = 'CASH' ) 
    and  h1.customer_no = p.customer_no 
    group by h1.customer_no

    union

    select to_char(h1.payment_date, 'MM/DD/YYYY') , h1.customer_no
    from payments h1 inner   join ( select customer_no, max(payment_date ) as max_date from payments where ctype = 'CASH'  group by customer_no ) subQ
    on  ( h1.customer_no = subQ.customer_no
    and h1.payment_date = subQ.max_date   ) 
    and  h1.customer_no = p.customer_no 
    group by h1.payment_date, h1.customer_no ) sq,

  payments p
  where  p.customer_no = 400
  and sq.customer_no = p.customer_no 

当我运行它时,我得到ORA-00904:“P”。“CUSTOMER_NO”:标识符无效。我需要将h1.customer_no加入外部查询customer_no。

我已经看到了一些排名但我无法弄明白的问题。如何使用外部查询加入内部查询?

提前感谢。

1 个答案:

答案 0 :(得分:0)

您的付款表是否有customer_no列?这似乎是你的错误所表明的。

至于如何加入子查询,您可能需要查看factored subqueries。你可以这样做:

WITH z AS (
  SELECT ...
  UNION
  SELECT ...
), y AS (
  SELECT ...
)
SELECT ...
FROM y
JOIN z ON y.x = z.x
JOIN some_other_table t ON z.a = t.a