加入加倍的聚合,有时是三倍的数量

Joins with aggregates doubling, sometimes tripling quantity amounts

我正在尝试连接 4 个表以获得多列结果,其中两列是各自列的 sums/aggregates。我的查询返回的是真实总和的倍数。这是我拥有的:

select pl.[Vendor Item No_], bc.[Item No_], min(ile.[Description]) as 'Item Description',
        sum(ile.[Quantity]) as 'Quantity On Hand', 
        bc.[Bin Code] as 'Item Location'
 from [live$Bin Content]bc left outer join [live$purchase line]pl
  on bc.[Item No_] = pl.[No_]left outer join [live$item ledger entry] ile
  on bc.[Item No_] = ile.[Item No_]
where bc.[Bin Code] like 'ANNEX BACK'
and   bc.[Item No_] like 'sk%'


group by pl.[Vendor Item No_], bc.[Item No_], pl.[Description], bc.[Bin Code]

使用 subquery/inline 视图可能会解决您的问题。假设其他一切正常。要确定我们需要知道所有 3 个 table 之间的 PK/FK 关系。

SELECT pl.[Vendor Item No_], 
       bc.[Item No_], 
       min(ile.[Description]) as 'Item Description',
       ile.[Quantity] as 'Quantity On Hand', 
       bc.[Bin Code] as 'Item Location'
 FROM [live$Bin Content] bc 
 LEFT JOIN [live$purchase line] pl
  on bc.[Item No_] = pl.[No_]
 LEFT JOIN  (SELECT sum(quantity) as Quantity, [Item no_] 
             FROM [live$item ledger entry] 
             GROUP BY [Item no_]) ile
  on bc.[Item No_] = ile.[Item No_]
where bc.[Bin Code] like 'ANNEX BACK'
and   bc.[Item No_] like 'sk%'
group by pl.[Vendor Item No_], bc.[Item No_], pl.[Description], bc.[Bin Code]

根据评论...如果您想添加另一个 table 并合计数量...

   SELECT pl.[Vendor Item No_], 
           bc.[Item No_], 
           min(ile.[Description]) as 'Item Description',
           ile.[Quantity] as 'Quantity On Hand', 
           bc.[Bin Code] as 'Item Location'
     FROM [live$Bin Content] bc 
     LEFT JOIN [live$purchase line] pl
      on bc.[Item No_] = pl.[No_]
     LEFT JOIN  (SELECT sum(quantity) as Quantity, [Item no_] 
                 FROM [live$item ledger entry] 
                 GROUP BY [Item no_]) ile
      on bc.[Item No_] = ile.[Item No_]
     LEFT JOIN  (SELECT sum(NEWFIELD) as Quantity, [Item no_] 
                 FROM [newTable] 
                 GROUP BY [Item no_]) newAlias
      on bc.[Item No_] = newAlias.[Item No_]
    where bc.[Bin Code] like 'ANNEX BACK'
    and   bc.[Item No_] like 'sk%'
    group by pl.[Vendor Item No_], bc.[Item No_], pl.[Description], bc.[Bin Code]

但是,如果该字段在现有 table 之一中,您只需将其添加为子查询中的新字段...

SELECT pl.[Vendor Item No_], 
       bc.[Item No_], 
       min(ile.[Description]) as 'Item Description',
       ile.[Quantity] as 'Quantity On Hand', 
       bc.[Bin Code] as 'Item Location',
       ile.count as count of items with inventory in ILE.
 FROM [live$Bin Content] bc 
 LEFT JOIN [live$purchase line] pl
  on bc.[Item No_] = pl.[No_]
 LEFT JOIN  (SELECT sum(quantity) as Quantity, count(Quantity) as count, [Item no_] 
             FROM [live$item ledger entry] 
             GROUP BY [Item no_]) ile
  on bc.[Item No_] = ile.[Item No_]
where bc.[Bin Code] like 'ANNEX BACK'
and   bc.[Item No_] like 'sk%'
group by pl.[Vendor Item No_], bc.[Item No_], pl.[Description], bc.[Bin Code]