我正在尝试在应用具有多个表的左连接时获取行的总和。它似乎正在创建一个结果矩阵,导致错误的求和函数。
示例:
第一张表:客户
第二张表: TotalAssets
第三表: TotalLiability
表格结构:
客户
CustID(int) CustomerName(varchar)
1 Abc
2 Def
3 Ghi
TotalAssets
CustID Amount
1 2000
1 1000
2 600
TotalLiability
CustID Amount
1 1000
1 1000
2 800
预期输出
CustID TotalAssets TotalLiability
1 3000 2000
2 600 800
当前查询
Select c.CustID , Sum(a.Amount) , Sum(l.Amount) From Customer c
left join TotalAssests a on a.CustID = c.CustID
left join TotalLiability l on l.CustID = c.CustID
Group by c.CustID
这个当前查询的问题是总和不正确,因为我认为第一个左连接创建了一个包含多个记录的第一个集合,然后应用了第二个。
感谢任何帮助
更新
我通过以下方法找到了一些运气,但它似乎是一个糟糕/ hacky选项,因为在我的情况下,我在组中有超过7-8个元素,并添加更多左子句导致查询难以管理。
新查询导致了正确的结果,但看起来很难维护
Select Set1.CustID , Set1.TotalAssets, Sum(l.Amount) from (Select c.CustID , Sum(a.Amount) as TotalAssets From Customer c
left join TotalAssests a on a.CustID = c.CustID
Group by c.CustID)Set1
left join TotalLiability l on l.CustID = Set1.CustID.
Group by Set1.CustID , Set1.TotalAssets
答案 0 :(得分:4)
我认为这会以最小的复杂性为您提供您想要的东西:
select c.CustId, isnull(a.Amount, 0) as TotalAssets, isnull(l.Amount, 0) as TotalLiability
from Customers c
left join (
select CustId, sum(Amount) as Amount from TotalAssets group by CustId
) a on a.CustId = c.CustId
left join (
select CustId, sum(Amount) as Amount from TotalLiability group by CustId
) l on l.CustId = c.CustId
您需要分别对两个表进行分组/求和,因为它们中的数据是独立的。左连接到customers表确保仍然报告在两个/两个表中都没有条目的客户。
答案 1 :(得分:0)
这应该有效:
Select c.CustID
, (select sum(a.amount) from TotalAssests a where a.CustId = c.CustID) as SumAsset
, (select Sum(l.Amount) TotalLiability l where l.CustID = c.CustID) as SumLiability
From Customer c
答案 2 :(得分:-2)
希望以下工作减少维护,
DECLARE @Customer TABLE (CustID int, CustomerName varchar(50)) DECLARE @TotalAssets TABLE (CustID int, Amount INT) DECLARE @TotalLiability TABLE (CustID int, Amount INT)
INSERT INTO @Customer
SELECT 1,
'ABC'
UNION
SELECT 2,
'DEF'
UNION
SELECT 3,
'GHI'
--Select * From @Customer
INSERT INTO @TotalAssets
SELECT 1,
2000
UNION
SELECT 1,
1000
UNION
SELECT 2,
600
--Select * From @TotalAssets
INSERT INTO @TotalLiability
SELECT 1,
1000
UNION
SELECT 1,
1000
UNION
SELECT 2,
800
--Select * From @TotalLiability
SELECT *
FROM @Customer
SELECT C.CustID,
C.CustomerName,
Sum(A.Amount) TotalAssets,
Sum(L.Amount) TotalLiability
FROM @Customer C
JOIN @TotalAssets A ON C.CustID = A.CustID
JOIN @TotalLiability L ON C.CustId = L.CustID
GROUP BY C.CustID,
C.CustomerName