2016-04-15 86 views
0

我正在嘗試檢索與發票相關的數據。每張發票有多個記錄,原始發票,付款,信用。我需要基於兩個字段的數據,record_type(I =發票,C =信用,P =付款...)和來源(B =結算,C =現金收據...)。需要根據兩個條件檢索多行數據

我需要將檢索到的記錄限制爲source = B,並獲取record_type的所有記錄<> P,但是存在record_type = C的記錄。

實施例的數據集:

Invoice  Amount  record_type  source --comment 
    12345  100  I    B  original invoice 
    12345  -100  C    B  credit memo 
    12345  80   I    B  revised invoice 
    12345  -80  P    C  payment 
    23456  200  I    B  original invoice 
    23456  -10  C    C  cash receipt adjust 
    34567  300  I    B  original invoice 

檢索到的記錄應該是:

Invoice  Amount  record_type  source --comment 
    12345  100  I    B  original invoice 
    12345  -100  C    B  credit memo 
    12345  80   I    B  revised invoice 

這裏是我到目前爲止的代碼。

SELECT 
     ot.order_id, 
     ot.customer_id, 
     c.name, 
     ot.gl_date, 
     ot.amount, 
     ot.record_type, 
     ot.source 

    FROM open_item ot 
     JOIN customer c ON c.id = ot.customer_id and 
     c.company_id = 'TMS' 
     JOIN orders o ON o.id = ot.order_id 

    WHERE 
     ot.source = 'B' AND 
     ot.gl_date >= {d '2016-03-01'} AND 
     ot.gl_date <= {d '2016-03-31'} AND 
     ot.record_type <> 'P' AND 
    EXISTS (SELECT 1 FROM open_item ot2 
     WHERE ot2.order_id = ot.order_id AND 
     ot2.record_type = 'C' AND ot2.source = 'B') 

    ORDER BY 
     ot.order_id 

感謝@GordonLinoff爲我提供了幫助。 我也收到了一個基於我的ORDERBY的錯誤,但這是目前的一個小問題。

回答

0

將record_type = C的訂單標準移至內部聯接。

SELECT 
    ot.order_id, 
    ot.customer_id, 
    c.name, 
    ot.gl_date, 
    ot.amount, 
    ot.record_type, 
    ot.source 

FROM open_item ot 
    JOIN customer c ON c.id = ot.customer_id and 
    c.company_id = 'TMS' 
    JOIN orders o ON o.id = ot.order_id 
    JOIN open_item ot2 ON ot2.order_id = ot.order_id AND ot2.record_type = 'C' 
WHERE 
    ot.source = 'B' AND 
    ot.gl_date >= {d '2016-03-01'} AND 
    ot.gl_date <= {d '2016-03-31'} AND 
    ot.record_type <> 'P' 
ORDER BY 
    ot.order_id 
+0

工作正常。謝謝!現在要弄清楚爲什麼ORDER BY不起作用。關於不被包含在聚合函數或GROUP BY子句..... –

+0

我看不到任何聚合數據的查詢。是否有任何代碼之前或之後可能會產生此錯誤或與此查詢相關聯? – dbbri

+0

對於具有「C」record_type和「C」源的記錄,它僅列出具有「I」record_type的記錄。在我的示例數據集中,只有第一行發票23456正在顯示,因此我試圖省略這一點。 –

0

我使用@dbbri答案並添加了一個附加條件。

FROM open_item ot 
    JOIN customer c ON c.id = ot.customer_id and 
    c.company_id = 'TMS' 
    JOIN orders o ON o.id = ot.order_id 
    JOIN open_item ot2 ON ot2.order_id = ot.order_id 
    AND ot2.record_type = 'C' 
    **AND ot2.source = 'B'**