SQL SERVER MULTIPLE JOIN:避免重复值

时间:2016-08-04 10:37:03

标签: sql-server join

我的数据库中有3个表: -

客户:

 CId | CName | CLocation | CJoinDate

付款:

TxnId | TxStatus | TxComment | TxAmount | CId | TxDate

预约:

AppId | AppCode | CId | ADate | AComment

当我使用两个表进行左连接时,计算结果正确。但是当我尝试连接3个表时,计算结果是错误的。

例如: -

如果我尝试此查询,则计算的总金额是正确的:

SELECT c.CName, sum(p.TxAmount) 
FROM Customer c LEFT JOIN Payment p ON c.CId = p.CId 
WHERE p.TxStatus = 1 
GROUP BY c.CName;

在上面的查询中,我只是加入了两个表,它们给出了正确的结果。

现在,当我想在一个表中显示所有记录时,我必须加入3个表。 以下是我试过的查询:

SELECT c.CName as Name, sum(p.TxAmount) as Payment, count(distinct a.ADate) as Total_Visit 
FROM Customer c LEFT JOIN Payment p ON c.CId = p.CId LEFT JOIN Appointment a ON c.CId = a.CId
WHERE p.TxStatus = 1 
GROUP BY c.CName;

以上查询给出了每个客户的错误付款金额。错误结果的原因是Appointments表与每个客户的Payment表相比有更多行。因此,为了显示所有约会条目,付款金额会重复,因为计算错误。

如何使用上述查询修复上述情况。

韩国社交协会

编辑:实际上还有2-3个表,我必须加入类似于约会表的表,以及每个月的GROUP BY子句。

EDIT1:通过多次CTE修复它。感谢您的宝贵指示,这确实很有帮助。

3 个答案:

答案 0 :(得分:1)

如果您确定第一个查询正确计算了总和

,请使用简单的CTE表达式
WITH cte AS 
(
SELECT c.CName, c.CID, sum(p.TxAmount) AS sumAmount
FROM Customer c LEFT JOIN Payment p ON c.CId = p.CId 
WHERE p.TxStatus = 1 
GROUP BY c.CName, c.CID 
)
SELECT cte.CName, cte.sumAmount, count(distinct a.ADate) as Total_Visit
FROM cte LEFT JOIN Appointment a ON c.CId = a.CId
GROUP BY c.CName, cte.sumAmount

答案 1 :(得分:0)

尝试使用子查询:

SELECT 
c.CName as Name
, sum(p.TxAmount) as Payment
, Total_Visit = (SELECT count(distinct a.ADate) FROM Appointment a ON c.CId = a.CId)
FROM Customer c 
LEFT JOIN Payment p ON c.CId = p.CId 
WHERE p.TxStatus = 1 
GROUP BY c.CName;

答案 2 :(得分:0)

您可以计算每个CId的total_visit,然后加入子查询

SELECT 
  c.CName as Name
, sum(p.TxAmount) as Payment
, Total_Visit 
FROM Customer c 
LEFT JOIN Payment p ON c.CId = p.CId 
LEFT JOIN (SELECT a.CId, count(distinct a.ADate) Total_visit FROM Appointment a group by a.CId) as a on c.CId = a.CId 
WHERE p.TxStatus = 1 
GROUP BY c.CName;