2017-07-28 89 views
0

過濾我有兩個表: 表1連接兩個表 - 在2個獨立的條件

Customer|Seller Currency|Invoice #|Invoice Currency 

ABC  |USD   |123  |MXP 

我有一個第二表,其中我存儲我的客戶

表2的銀行帳戶

Customer | Bank Account | Currency 
ABC  | BANK1  | MXP 
ABC  | BANK2  | INP 
ABC  | BANK3  | USD 

我想加入這兩個表,所以當我creati NG的儀表板,我可以顯示以下內容:

如果客戶ABC在發票幣種的銀行帳戶,然後顯示,銀行賬戶(在這種情況下,結果將是BANK1)

如果客戶沒有銀行賬戶發票的貨幣,然後顯示在客戶的貨幣的銀行賬戶(在這種情況下,將區塊3

別的不顯示「沒有有效的銀行帳戶」

當我「M加入我的表是將多個記錄....我怎麼能做到這一點?

+0

您正在使用什麼數據庫? – Alex

+0

什麼你嘗試到現在? – 31piy

回答

1

讓我們把你的兩個表customer_invoicescustomer_accounts

您可以使用下面的查詢與 LEFT JOIN S(所以,如果沒有銀行賬戶的存在,我們仍然保持留下數據,以及一個GROUP BY(萬一有人在給定的貨幣不止一個銀行賬戶,我們不顯示全部):

SELECT 
    customer_invoices.customer, 
    customer_invoices.seller_currency, 
    customer_invoices.invoice_number, 
    customer_invoices.invoice_currency, 
    coalesce(min(account_invoice_currency.bank_account), 
       min(account_seller_currency.bank_account), 
       'no valid bank account') AS chosen_bank_account 
FROM 
    customer_invoices 
    LEFT JOIN customer_accounts AS account_seller_currency 
     ON  account_seller_currency.customer = customer_invoices.customer 
      AND account_seller_currency.currency = customer_invoices.seller_currency 
    LEFT JOIN customer_accounts AS account_invoice_currency 
     ON  account_invoice_currency.customer = customer_invoices.customer 
      AND account_invoice_currency.currency = customer_invoices.invoice_currency 
GROUP BY 
    customer_invoices.customer, customer_invoices.seller_currency, 
    customer_invoices.invoice_number, customer_invoices.invoice_currency ; 

您將獲得:

 
customer | seller_currency | invoice_number | invoice_currency | chosen_bank_account 
:------- | :-------------- | -------------: | :--------------- | :------------------ 
ABC  | USD    |   123 | MXP    | BANK1    

您可以在dbfiddle檢查整個安裝here


參考文獻: