2010-12-01 124 views
1

SQL在下面 - 每個結果出現3次而不是僅僅一次。爲什麼我的SQL查詢返回重複結果?

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是給我的另一個類似的查詢,但這個時候,我已經修改了它嘗試使用它,現在我做的查詢,所以我假設我做的事笨。

非常感謝。

回答

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

3

可能是因爲您的左連接每個父行有3個子行。 做一個select *來查看你的結果在相乘的行中會有不同的結果。