0

我有三个表 1. ItemMaster 2. GRN 3. 问题

Item Master
------------------
ItemCode          ItemDescr
--------          ---------
1                 Test1
2                 Test2
3                 Test3
4                 Test4
5                 Test5

GRN Table
-------------------
ItemCode          grnQty
--------         --------
1                 1
1                 2
2                 1
1                 2
2                 1
3                 1

Issue Table

ItemCode         issQty
--------         -------
1                 1
1                 2
2                 1
4                 1

我想生成一个报告/视图,例如 ->

ItemCode          ItemDescr      GRN Qty      Issue Qty  
--------          ---------      -------      ---------         
1                  Test1          5              3                 
2                  Test2          2               1                 
3                  Test3          1               0
4                  Test4          0               1
5                  Test5          0               0

为此,我使用了以下 sql 代码:

select a.ItemCode, a.ItemDescr, isnull(sum(b.grnQty),0) as 'GRN Qty', isnull(sum(c.issQty),0) as 'Issue Qty' from
ItemMaster a
left join GRN b
on a.ItemCode=b.ItemCode
left join Issue c
on a.ItemCode=c.ItemCode
group by a.ItemCode, a.ItemDescr

但生成的报告是

ItemCode          ItemDescr      GRN Qty      Issue Qty  
--------          ---------      -------      ---------         
1                  Test1          10              9                 
2                  Test2          2               2                 
3                  Test3          1               0
4                  Test4          0               1
5                  Test5          0               0

我的代码有什么问题???

GRN 数量 10=5 X(项目代码 1 的问题表中的行数)和问题数量 9 = 3 X 等其他值相同(项目代码 2 的 GRN 表中的行数)可能只是巧合

请帮忙。

4

1 回答 1

1

这里没有信心,你所描述的正是你的问题。请看简化查询的结果:

select a.ItemCode, a.ItemDescr, b.grnQty as 'GRN Qty', c.issQty as 'Issue Qty' 
from ItemMaster a
left join GRN b on a.ItemCode=b.ItemCode
left join Issue c on a.ItemCode=c.ItemCode

这个表看起来像(只是 ItemCode=1 的行):

ItemCode          ItemDescr      GRN Qty      Issue Qty  
--------          ---------      -------      ---------         
1                  Test1         1            1                 
1                  Test1         2            1                 
1                  Test1         2            1                 
1                  Test1         1            2                 
1                  Test1         2            2                 
1                  Test1         2            2                

现在通过 + summing end 添加您的组,您最终会到达您所在的位置。

因此,您不能直接对具有两个连接的选择进行求和,因为您最终会得到连接的所有排列。

所以子查询在这里可以提供帮助:

select 
    a.ItemCode, 
    a.ItemDescr, 
    (select sum(b.grnQty) from GRN b where a.ItemCode=b.ItemCode) as 'GRN Qty', 
    (select sum(c.issQty) from Issue c where a.ItemCode=c.ItemCode) as 'Issue Qty' 
from ItemMaster a
于 2013-06-29T15:43:05.577 回答