我正在尝试连接4个表来获得几列结果,其中两列是各自列的总和/聚合。我的查询返回真实总和的倍数。这就是我所拥有的:
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]
答案 0 :(得分:1)
使用子查询/内联视图可以解决您的问题。假设其他一切正常。要确定我们需要知道所有3个表之间的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]
每条评论...如果您想添加另一张表并汇总数量......
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]
但是,如果该字段位于其中一个现有表中,则只需将其添加为子查询中的新字段...
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]