0

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

     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": invalid identifier。我需要将 h1.customer_no 加入外部查询 customer_no。

我见过一些有排名的查询,但我不太明白。如何将内部查询与外部查询连接起来?

提前致谢。

4

1 回答 1

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 
于 2013-02-26T22:45:38.447 回答