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

Yar*_*994 2 sql-server join group-by case conditional-aggregation

我需要按 2 列(BillingId 和 PaymentType)对数据进行分组 - 没有问题,并且输出 1 行,其中包含唯一的 PaymentType 列- 此步骤存在问题。因此,每个 BillingId 只有 1 行,该表将用于连接数据库中的另一个表。

计费表:

BillingId (unique)

 12345
 67890

Run Code Online (Sandbox Code Playgroud)

付款表:

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
Run Code Online (Sandbox Code Playgroud)

我的代码:

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
Run Code Online (Sandbox Code Playgroud)

输出(显然不正确):

  BillingId  PaymentType   AmountPaid

     67890    electronic    83.58
     12345    electronic    73.28
     67890    adjustment    30.43
Run Code Online (Sandbox Code Playgroud)

我需要的输出:

BillingId    AmountPaid     AmountAdjusted 
            (electronic)     (adjustment)

  67890         83.58           30.43
  12345         73.28            0

Run Code Online (Sandbox Code Playgroud)

Ant*_*rig 6

如果使用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
Run Code Online (Sandbox Code Playgroud)

数据库<>小提琴

帐单ID 支付金额(电子) 调整金额(调整)
12345 73,28 无效的
67890 83,58 30,43