加入两个表 - 在两个不同的条件下过滤

时间:2017-07-28 00:35:19

标签: postgresql join filter

我有两张桌子: 表1

Customer|Seller Currency|Invoice #|Invoice Currency

ABC     |USD            |123      |MXP

我有第二张表,用于存储客户的银行帐户

表2

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

我想加入这两个表,以便在创建仪表板时我可以显示以下内容:

如果客户ABC拥有发票货币的银行账户,则显示该银行账户(在这种情况下结果将是bANK1)

如果客户没有发票货币的银行帐户,则以客户的货币显示银行帐户(在这种情况下,它将是Bank3

其他任何内容确实显示"没有有效的银行帐户"

当我加入我的牌桌时,它会带来多条记录......我怎样才能实现这个目标?

1 个答案:

答案 0 :(得分:1)

让我们拨打您的两个表customer_invoicescustomer_accounts

您可以对两个 LEFT JOIN使用以下查询(因此,如果没有银行帐户,我们仍会保留左侧数据,还有一个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

中查看整个设置

参考文献: