簡體   English   中英

GROUP BY 並為分組的每個唯一值創建列(始終輸出為 1 行),然后使用 output 作為 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 行的 output 和唯一的 PaymentType 列——這一步有問題。 所以每個 BillingId 只有 1 行,該表將用於連接數據庫中的另一個表。

計費表:

BillingId (unique)

 12345
 67890

付款表:

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

OUTPUT(顯然不正確):

  BillingId  PaymentType   AmountPaid

     67890    electronic    83.58
     12345    electronic    73.28
     67890    adjustment    30.43

OUTPUT 我需要:

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<>小提琴

帳單編號 支付金額(電子版) AmountAdjusted(調整)
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;

請參閱演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM