0

我几乎可以肯定我以前遇到过这种情况并且只是有一个扩展的高级时刻,但我试图从 SQL 实例上跨 2 个数据库的三个不同表中提取工作订单数据并将其全部合并到一个报告中,我'正在寻找包含以下列的最终结果:

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

方差部分很简单,我可以嵌套 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),但是如果我从报告中删除一个数据点并仅选择库存或生产数量,我会得到正确的最终结果。我发誓我以前遇到过这个问题,但是我一生都不记得它是如何解决的,如果这也是一个重复的问题,对不起,通过搜索找不到任何东西。

提前感谢您的帮助,非常感谢。

4

1 回答 1

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 示例

如果你有 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 示例

发生这种情况是因为当你加入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 的每一行,表中将有 6 行 WO = 152 Production,因此您总共将有 30 行并且QTY从库存中将列出 6 次。当你总结时,你将有 75 * 6 = 450 而不是 75。因为Count你将拥有每个Count* 5,所以你将拥有 200 而不是 40。

于 2012-11-30T14:16:25.747 回答