2013-02-26 47 views
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」:無效的標識符。我需要將h1.customer_no加入外部查詢customer_no。

我已經看到一些排名查詢,但我無法弄清楚。如何使用外部查詢加入內部查詢?

在此先感謝。

回答

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