我正在尝试执行查询以显示客户余额以及多项客户相关费用的总和,以便我可以检查总余额是否与合并余额相匹配。
我认为我需要在查询中使用GROUP BY,但到目前为止它已被证明是不成功的。我的尝试如下:
select c.ID, m.Balance, SUM(chg.Balance) as CombinedBalance
from Customer c
INNER JOIN ChargeTemplate chg
on c.ID = chg.CustomerID
WHERE c.Balance <> (SELECT SUM(Balance) FROM ChargeTemplate WHERE chg.CustomerID= c.ID )
GROUP BY c.ID, c.Balance
order by c.ID ASC
以上查询输出总余额和总余额余额,但同时显示c.Balance
等于合并余额的记录。
以下查询与上述查询完全相同,即使我已删除了WHERE子句。
select c.ID, c.Balance, SUM(chg.Balance) as CombinedBalance
from Customer c
INNER JOIN ChargeTemplate chg
on c.ID = chg.CustomerID
GROUP BY c.ID, c.Balance
order by c.ID ASC
我想要的输出是CUSTOMERTABLE.BALANCE
值以及相应的客户费用总和 - 这样,我可以将实际余额与合计金额进行比较。我怎样才能实现这一目标?
注意:费用表具有CustomerTable.CustomerID FK
客户1:
CUSTOMERTABLE.TOTAL_BALANCE = 100.00
CHARGETABLE.CHARGE[1].BALANCE = 20.00
CHARGETABLE.CHARGE[2].BALANCE = 30.00
CHARGETABLE.CHARGE[3].BALANCE = 50.00
客户2:
CHARGETABLE.CHARGE[1].BALANCE = 10.00
CHARGETABLE.CHARGE[2].BALANCE = 20.00
CHARGETABLE.CHARGE[3].BALANCE = 30.00
CHARGETABLE.CHARGE[4].BALANCE = 90.00
CHARGETABLE.CHARGE[5].BALANCE = 50.00
答案 0 :(得分:3)
要过滤聚合,请使用HAVING子句
Select
c.ID, m.Balance, Sum(chg.Balance) as CombinedBalance
From
Customer c
Inner Join
ChargeTemplate chg
On c.ID = chg.CustomerID
Group By
c.ID, c.Balance
Having
m.Balance != Sum(chg.Balance)
Order By
c.ID ASC