由于我的联接不正确而获取重复的行

时间:2019-07-17 22:18:16

标签: sql qsqlquery

我创建了一个查询,该查询在添加第三个连接之前一直有效,并且它们得到重复的行。我对此很陌生,希望也许有人能很快找到问题。我已经插入了代码。

我已经尝试了多种方法,但目前仍处于困境。

With Inv_Amount As
(
SELECT 
 l.[Document No_] As DocNum
,Sum(l.[Amount]) As Amount
,Sum(l.[Unit Cost]) As Unit_Cost


FROM [JF-FSProd].[dbo].[Inc_$Sales Invoice Header] h With (NOLOCK)
   Join [JF-FSProd].[dbo].[Inc_$Sales Invoice Line] l With (NOLOCK) on h.No_ = l.[Document No_] 
   Join [JF-FSProd].[dbo].[Inc_$EFT Transaction] e With (NOLOCK) on h.[No_] = e.[Document No_]
   Join [JF-FSProd].[dbo].[Inc_$Customer] c With (NOLOCK) on h.[Sell-to Customer No_] = c.No_

Where c.[D2C Customer] = 1 --D2C Custs only
and l.[No_] not in ('23215','53100') -- Only pulls in lines that are revenue and not G/L lines for shipping and tax
Group By l.[Document No_]
)

SELECT 
     h.[Sell-to Customer No_] As Cust_Num
    ,h.[No_] As Doc_Num
    ,h.[Order Date] As Order_Date
    ,a.Amount
    ,h.[D2C Order No_] As D2C_Order_Num
    ,e.[Document No_] As EFT
    ,e.[Account Type] As Credit_Card_Type
    ,h.[Sell-to County] -- State where sales was shipped
    ,a.[Unit_Cost] As Unit_Cost
FROM [JF-FSProd].[dbo].[Inc_$Sales Invoice Header] h With (NOLOCK)
  Join [JF-FSProd].[dbo].[Inc_$EFT Transaction] e With (NOLOCK) on h.[No_] = e.[Document No_]
  Join [JF-FSProd].[dbo].[Inc_$Customer] c With (NOLOCK) on h.[Sell-to Customer No_] = c.No_
  Join Inv_Amount a on h.[No_] = a.DocNum
Where c.[D2C Customer] = 1 --D2C Custs only
    and a.Amount <> 0

我希望只有1行,但每条记录会得到2行。

E00916 EINV100000 2018-06-20 00:00:00.000 35.20000000000000000000 E00916 EINV100000 2018-06-20 00:00:00.000 35.20000000000000000000 E00915 EINV100001 2018-06-20 00:00:00.000 179.84000000000000000000
E00915 EINV100001 2018-06-20 00:00:00.000 179.84000000000000000000
E00911 EINV100002 2018-06-20 00:00:00.000 215.12000000000000000000
E00911 EINV100002 2018-06-20 00:00:00.000 215.12000000000000000000

1 个答案:

答案 0 :(得分:0)

似乎Inv_Amount表具有“重复”值。尝试执行此操作以确认SELECT DocNum, COUNT(DocNum) FROM Inv_Amount GROUP BY DocNum。查看给定的结果集,这应证明DocNum EINV100002至少有2条记录。

在这种情况下,请尝试另外的GROUP BY查询以限制重复的结果,然后再加入该查询,而不是单纯地加入Inv_Amount表。