交易值大于或小于零的组发票

时间:2012-11-05 21:17:48

标签: sql join

我试图提出一个问题,但我还没有运气。表格如下:

INVOICE
ID | INVOICENUMBER | CUSTOMER | VALUE
1 | 999 | 8 | 9000
2 | 999 | 8 | 1000


INVOICE_TRANSACTION
InvoiceID | TYPE | VALUE
1 | cust | 5000
1 | cust | 2000
2 | cust | 1000
2 | cust | -1000

INVOICE_DETAIL
InvoiceID | PURCHASEORDERID
1 | 7777

PURCHASE_ORDER
PURCHASEORDERID | ORDERTYPE
7777 | gross

PURCASE_ORDER_DETAILS
PURCHASEORDERID | ROW | STATUS
7777 | 1 | 1
7777 | 2 | 2
7777 | 3 | 3

我想要的结果是:

INVOICE VALUE TRANSACTION VALUE PURCHASEORDERID ORDERTYPE HIGH STATUS LOW STATUS
------- ----- ----------------- --------------- --------- ----------- ----------
1       9000  7000              7777            gross     3           1

换句话说,我希望结果将总计invoice_transaction.value大于或小于0的所有发票编号分组。我对这一切都不熟悉,任何人都可以帮我开始吗?< / p>

2 个答案:

答案 0 :(得分:2)

看起来你想要这样的东西:

select i.id,
  sum(i.value) value,
  it.value TransValue,
  p.purchaseorderid,
  p.ordertype,
  pd.highstatus,
  pd.lowstatus
from invoice i
left join 
(
  select sum(value) value, invoiceid
  from invoice_transaction
  group by invoiceid
) it
  on i.id = it.invoiceid
left join invoice_detail id
  on i.id = id.invoiceid
left join purchase_order p
  on id.purchaseorderid = p.purchaseorderid
left join
(
  select max(status) highStatus, min(status) LowStatus,
    purchaseorderid
  from purcase_order_details
  group by purchaseorderid
) pd
  on p.purchaseorderid = pd.purchaseorderid
where it.value <> 0
group by i.id, p.purchaseorderid, p.ordertype;

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

要从INVOICE_TRANSACTION获取发票ID,其中值不为零,

SELECT InvoiceID
FROM INVOICE_TRANSACTION
GROUP BY InvoiceID
HAVING SUM(VALUE) <> 0