SQL多个1对多连接

时间:2012-11-30 13:37:44

标签: sql join

我几乎可以肯定我以前遇到过这个问题并且只是在延长高级时刻,但是我试图在SQL实例上从2个db中的三个不同表中提取工作订单数据并将它们全部合并到一个报告,我正在寻找包含以下列的最终结果:

WO |生产记录数量|库存数量|方差

Variance部分很容易我可以嵌套select语句,并在外部语句中减去两个数量,但我遇到的问题是当我加入相应数据库中的生产和库存表时我结束了获得我所针对的列的总和比它们应该更大的列

示例数据:

Work Order, Short P/N, and Long P/N in Work Order Table:
dba.1       
WO  ShortPN LongPN
152 1234    Part1

Short P/N, Quantity on hand, location, and lot # in inventory table:
dba.2           
ShortPN Qty Loc   Lot
1234    31  Loc1  456
1234    0   Loc2  456
1234    0   Loc4  456
1234    19  Loc1  789
1234    25  Loc4  789

Work Order, Long P/N, and production count of the last 5min in Production table:
dbb.3       
WO  LongPN  Count
152 Part3   6
152 Part3   8
152 Part3   9
152 Part3   4
152 Part3   6
152 Part3   7

With this example I've tried:

SELECT 1.WO AS WO
   ,SUM(2.Qty) AS "Qty On Hand"
   ,SUM(3.Count) AS "Produced Qty"

FROM dba.1
INNER JOIN dbb.2 ON 1.ShortPN=2.ShortPN
INNER JOIN dbb.3 ON 1.WO = 3.WO    
GROUP BY 1.WO

我也尝试从3中选择,在WO上加1到3,然后在shortPN上加2到1,并且两者都产生比它们应该指数级高的SUM()数(即应该是15,xxx变成超过2,000,000),但如果我从报告中删除其中一个数据点并仅选择库存或生产数量,我会得到正确的最终结果。我发誓以前我遇到过这个问题,但是因为我的生活不记得它是如何解决的,对不起,如果这也是一个重复的问题,通过搜索找不到任何东西。

在此先感谢您的帮助,非常感谢。

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情

select
    WO.WO, isnull(i.Qty, 0) as Qty, isnull(p.[Count], 0) as [Count]
from WorkOrder as WO
    left outer join (select t.ShortPN, sum(t.Qty) as Qty from inventory as t group by t.ShortPN) as i on
        i.ShortPN = WO.ShortPN 
    left outer join (select t.WO, sum(t.[Count]) as [Count] from Production as t group by t.WO) as p on
        p.WO = WO.WO 

SQL FIDDLE example

如果你有SQL Server 2005或更高版本,你可以像这样写

select
    WO.WO, isnull(i.Qty, 0) as Qty, isnull(p.[Count], 0) as [Count]
from WorkOrder as WO
    outer apply (select sum(t.Qty) as Qty from inventory as t where t.ShortPN = WO.ShortPN) as i
    outer apply (select sum(t.[Count]) as [Count] from Production as t where t.WO = WO.WO) as p

SQL FIDDLE example

这种情况发生了,因为当您加入WOinventory表时,

WO  SHORTPN QTY
-------------------
152 1234    31
152 1234    0
152 1234    0
152 1234    19
152 1234    25

并且您看到现在您有5行,其中WO = 152.当您使用Production表添加联接时,对于此联接中WO = 152的每一行,将有来自{的WO = 152的6行{1}}表格,因此您将共有30行,而库存中的Production将分别列出6次。总结一下,而不是75,你将得到75 * 6 = 450.对于QTY,你将每个Count * 5,所以不是40,你将有200。