2017-08-09 66 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); 

如果需要,请相应地更改您的表格和列名称。

相关问题