4

我正在尝试执行查询以显示客户余额以及几个客户相关费用的总金额,以便我可以检查总余额是否与合并余额相匹配。

我想我需要在查询中使用 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与客户费用的相应组合总和的值 - 这样,我可以比较实际余额与组合金额是否匹配。我怎样才能让这成为现实?

注意:chargetable 有一个 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
4

1 回答 1

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
于 2013-07-26T13:12:24.880 回答