Need to retrieve mutliple rows of data based on two criteria

时间:2016-04-15 14:47:35

标签: sql-server

I am trying to retrieve data related to invoices. There are multiple records per invoice, the original invoice, payments, credits. I need data based on two field, record_type (I=invoice,C=credit,P=payment...) and source (B=billing, C=cash receipt...).

I need to restrict the retrieved records to source = B, and get all records of record_type <> P, but where there is a record_type = C existing.

Example dataset:

    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

The retrieved records should be:

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

Here is the code I have so far.

    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

Thanks to @GordonLinoff for the help getting me this far. I also get an error based on my ORDERBY, but that's a small issue for now.

2 个答案:

答案 0 :(得分:0)

Moved your criteria for order with record_type=C to an inner join.

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

答案 1 :(得分: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'**