我需要按 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 …Run Code Online (Sandbox Code Playgroud)