为什么我的SQL查询返回重复的结果?

时间:2010-12-01 14:18:52

标签: c# asp.net sql

SQL在下面 - 每个结果出现3次而不是一次。

SELECT Consignments.LegacyID, TripDate, CollectionName, DeliveryName, Pallets, Weight, BaseRate, Consignments.FuelSurcharge, AdditionalCharges, BaseRate * Quantity AS 'InvoiceValue', Consignments.Customer, InvoiceNumber,
       CASE
          WHEN child.LegacyID = Consignments.Customer THEN child.LegacyID
          WHEN parent.LegacyID = Consignments.Customer THEN parent.LegacyID
          ELSE this.LegacyID
       END AS 'InvoiceAcc'
FROM SageAccount this
  LEFT JOIN SageAccount parent on parent.LegacyID = this.InvoiceAccount
  LEFT JOIN SageAccount child on this.LegacyID = child.InvoiceAccount
  JOIN Consignments on (Consignments.Customer = this.LegacyID AND this.Customer = 'True')
                    OR (Consignments.Customer = parent.LegacyID AND parent.Customer = 'True')
                    OR (Consignments.Customer = child.LegacyID AND child.Customer = 'True')
WHERE (this.LegacyID = @Customer) AND (TripDate BETWEEN @fromdate AND @todate) AND (InvoiceNumber IS NOT NULL)

SQL给了我另一个类似的查询,但是这次我修改了它以尝试将它用于我现在正在做的查询,所以我假设我做了一些愚蠢的事。

非常感谢。

2 个答案:

答案 0 :(得分:3)

可能是因为您的左连接每个父行有3个子行。 做一个select *来查看你的结果在成倍增加的行中的实际差异。

答案 1 :(得分:1)

JOIN Consignments on (Consignments.Customer = this.LegacyID AND this.Customer = 'True')
OR (Consignments.Customer = parent.LegacyID AND parent.Customer = 'True')
OR (Consignments.Customer = child.LegacyID AND child.Customer = 'True')

我猜你应该使用“this.InvoiceAccount”代替this.LegacyID