在 Firebird 中使用多个表连接避免重复值

Avoid duplicate values using join with multiple tables in Firebird

我有 3 table

付款

PaymntID Date Amount
1 Ago.2021 500
2 Sep.2021 1200
3 Oct.2021 600

现金支付

PaymntID Amount
1 500
2 400
3 200

信用卡支付

PaymntID Amount CreditCard
2 450 Visa
2 350 MC
3 400 Visa

我需要获取 PaymentID、日期、现金支付金额和信用卡支付金额,但通过以下查询我得到了重复项。

请注意,我可以在一次付款中使用两张不同的信用卡,但我也可以在一次付款中使用两种不同的“现金付款”。

查询:

select
PA.DATE AS PaymntDate,
PA.PaymntID AS PaymntID,
CP.amount AS CashAmount,
CCP.amount AS CreditAmount,

from Payments PA
    LEFT join CashPayments CP on PA.PaymntID = CP.PaymntID
    LEFT join CreditCardPayments CCP on PA.PaymntID = CCP.PaymntID

我得到以下结果:

结果

PaymntID PaymntDate CashAmount CreditAmount
1 Ago.2021 500 null
2 Sep.2021 400 450
2 Sep.2021 400 350
3 Oct.2021 200 400

所以在这种情况下,paymntid 2 中的现金支付是重复的。我需要的是以下 table:

结果

PaymntID PaymntDate CashAmount CreditAmount
1 Ago.2021 500 null
2 Sep.2021 400 800
3 Oct.2021 200 400

您需要在 加入之前 汇总每个 ID 的值。可能最简洁的方法是使用 CTE,然后将每个外部连接到您的 payments table,如下所示:

with cp as (
  select paymentId, Sum(Amount) Amount
  from CashPayments
  group by PaymentId
), ccp as (
  select paymentId, Sum(Amount) QAmount
  from CreditCardPayments
  group by PaymentId 
)
select p.PaymentId, p.Date,
  Coalesce(cp.Amount,0) CashAmount,
  Coalesce(ccp.Amount,0) CreditAmount
from Payments p
left join cp on cp.PaymentId = p.PaymentId
left join ccp on ccp.PaymentId = p.PaymentId