2017-08-09 48 views
0

我試圖從主表中選擇不同的值,並從子表中重複的值。 我有4個表:從主表中選擇不同的值,並從連接的表中重複值

  1. 發票
  2. invoiceLine
  3. 產品
  4. 業務夥伴

我的查詢:

select 
c_invoice.c_invoice_ID, 
c_bpartner.name as "Business Partner", 
M_Product.name as "Product", 
c_invoiceline.priceentered as "amount" 
from adempiere.c_invoice 
left join adempiere.c_invoiceline on c_invoice.c_invoice_ID=c_invoiceline.c_invoice_ID 
left join adempiere.M_Product on c_invoiceline.M_Product_ID =M_Product.M_Product_ID 
left join adempiere.C_BPartner on c_invoice.c_bpartner_ID=c_bpartner.c_bpartner_id 
where c_invoice.sh_booking_ID=1000019 and c_invoice.c_doctypetarget_id=1000005 

我的查詢結果:

INVOICEID BUSINESS Partner PRODUCT  AMT 
1000005; "Tehmoor";   "Charge 1"; 1200 
1000005; "Tehmoor";   "Standard"; 1500 
1000006; "Rafay";   "Charge 1"; 1200 
1000006; "Rafay";   "Standard"; 1100 

和預期的結果

INVOICEID BUSINESS Partner PRODUCT  AMT 
1000005; "Tehmoor";   "Charge 1"; 1200 
     ;  NULL;    "Standard"; 1500 
1000006; "Rafay";   "Charge 1"; 1200 
     ; NULL;    "Standard"; 1100 
+0

您有「業務合作伙伴」-eq null在預期結果的第二和第四行 - 爲什麼? –

+0

這是合乎邏輯的,因爲發票是爲單個業務合作伙伴創建的。 –

回答

1

你可以嘗試這樣的事情:

select 
    CASE WHEN row_number() OVER (PARTITION BY mast.id) = 1 THEN 
    mast.title 
    ELSE NULL END as title, 
    joined.measure 
from mast 
left join joined on (mast_id = mast.id) 

我已經創造了它fiddle,這樣你就可以檢查我的例子架構。 我認爲在主機語言中處理這種需求會更好,因爲在SQL中它有點棘手。

+1

謝謝哥們,這就是我一直在尋找的東西。 –

1

我在本地環境中複製了您的模式。以下是使用它可以實現所需結果的查詢。

SELECT 
CASE WHEN (Rank() Over(ORDER BY i.c_invoice_id ASC)) = (Row_Number() Over (ORDER BY i.c_invoice_id ASC)) THEN pt.b_name ELSE NULL END AS "Business Partner", 
CASE WHEN (Rank() Over(ORDER BY i.c_invoice_id ASC)) = (Row_Number() Over (ORDER BY i.c_invoice_id ASC)) THEN i.c_invoice_id ELSE NULL END AS Invoice_Id, 
pr.b_name, 
il.price 
FROM invoice i 
LEFT JOIN c_invoice_line il ON il.c_invoice_id = il.c_invoice_id 
LEFT JOIN c_product pr ON il.product_line_id = pr.b_prod_id 
LEFT JOIN c_bpartner pt ON pt.b_partner_id = Trim(il.c_prod_id); 

如果需要,請相應地更改您的表格和列名稱。

相關問題