GROUP BY 并为分组的每个唯一值创建列(始终输出为 1 行),然后将输出用作 JOIN - SQL 服务器

GROUP BY and create columns for each unique value grouped on (output as 1 row always), then use the output as a JOIN - SQL Server

我需要按 2 列(BillingId 和 PaymentType)对数据进行分组 - 没有问题并且 输出 1 行,其中的列具有唯一的 PaymentType - 此步骤存在问题。所以每个 BillingId 只有 1 行,table 将用于加入数据库中的另一个 Table。

计费Table:

BillingId (unique)

 12345
 67890

付款Table:

PaymentId PaymentType  BillingId PaymentAmount
 (unique)

   12      electronic    12345      62.29
   14      electronic    12345      73.28
   56      electronic    12345     -62.29
   6       electronic    67890      83.58
   2       adjustment    67890      30.43

我的代码:

SELECT GroupedTable.* 

FROM (SELECT b.BillingId, 
             p.PaymentType, 
             SUM(p.PaymentAmount) AS AmountPaid
      FROM Billing AS b
      LEFT JOIN Payment AS p
        ON (b.BillingId = p.BillingId)
      GROUP BY b.BillingId, p.PaymentType) AS GroupedTable

输出(显然不正确):

  BillingId  PaymentType   AmountPaid

     67890    electronic    83.58
     12345    electronic    73.28
     67890    adjustment    30.43

我需要的输出:

BillingId    AmountPaid     AmountAdjusted 
            (electronic)     (adjustment)

  67890         83.58           30.43
  12345         73.28            0

如果使用如下 Case When 表达式看起来更容易:

Select B.BillingId, Sum(Case When P.PaymentType='electronic' Then P.PaymentAmount End) As [AmountPaid (electronic)],
                    Sum(Case When P.PaymentType='adjustment' Then P.PaymentAmount End) As [AmountAdjusted (adjustment)] 
From Billing As B Left Join Payment As P On (B.BillingId=P.BillingId)
Group by B.BillingId

db<>fiddle

BillingId AmountPaid (electronic) AmountAdjusted (adjustment)
12345 73,28 NULL
67890 83,58 30,43

您应该仅按 BillingId 分组并使用条件聚合:

SELECT b.BillingId, 
       SUM(CASE WHEN p.PaymentType = 'electronic' THEN p.PaymentAmount ELSE 0 END) AS AmountPaid,
       SUM(CASE WHEN p.PaymentType = 'adjustment' THEN p.PaymentAmount ELSE 0 END) AS AmountAdjusted
FROM Billing AS b LEFT JOIN Payment AS p
ON b.BillingId = p.BillingId
GROUP BY b.BillingId;

参见demo