2016-04-15 85 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'**