我的连接查询返回了正确的值

时间:2016-08-25 07:40:03

标签: sql-server database join

我遇到问题,当我查询sql server以检索来自不同三个表的记录时,它执行SUM([Bills.Extrabill_dollar])SUM([Receipts.Amount])的完全错误的值,下面是我的查询,请帮助我。

select Customers.SNO, SUM(Bills.Extrabill_dollar) as [ExtraAmount],SUM(Receipts.Amount) as [Received]
from
Customers left join Bills on Customers.SNO=Bills.CustomerSNO
left join Receipts on Customers.SNO=Receipts.CSNO
group by Customers.SNO

但如果我使用两个单独的查询来返回 SUM(Extra_dollar) SUM(Extra_dollar)
SELECT Bills.CustomerSNO as [CustomerSNO], SUM(Bills.Extrabill_dollar) AS [TotalExtraAmount] from Bills group by Bills.CustomerSNO

SELECT Receipts.CSNO as [CustomerSNO], SUM(Receipts.Amount) AS [TotalReveied] from Receipts group by Receipts.CSNO如果使用 JOIN 合并这些表格,将会返回正确的结果,不会返回,请帮助我亲爱的。

3 个答案:

答案 0 :(得分:0)

说你的答案不正确,我不知道。

我认为既然您正在使用LEFT JOIN,那么可能会导致问题。 左连接从客户获取所有值,甚至会出现不匹配的行,这些行将被映射到Bills and Receipts下的NULL值。

您可以使用此代码进行试用。

SELECT Customers.SNO
, SUM(Bills.Extrabill_dollar) AS [ExtraAmount]
, SUM(Receipts.Amount) AS [Received]
FROM
Customers INNER JOIN Bills 
ON Customers.SNO=Bills.CustomerSNO
INNER JOIN Receipts 
ON Customers.SNO=Receipts.CSNO
GROUP BY Customers.SNO

答案 1 :(得分:0)

select Customers.SNO, SUM(Bills.Extrabill_dollar) as [ExtraAmount],SUM(Receipts.Amount) as [Received]
from
Customers right join Bills on Customers.SNO=Bills.CustomerSNO
right join Receipts on Customers.SNO=Receipts.CSNO
group by Customers.SNO

答案 2 :(得分:0)

亲爱的,感谢您的帮助,经过漫长的旅程,我找到了答案

select c.SNO, c.CName, 
isnull((select SUM(PricePerKwt_dollar) from Bills
where Bills.CustomerSNO =c.SNO),0.00) as [TotalBills],
isnull((select SUM(Receipts.Amount) from Receipts
where Receipts.CSNO = c.SNO),0.00) as [TotalReceipts]
 from Customers c