4

我有 3 表库存,向内,问题

库存表的列和数据:

part_no | part_name | totalqty
10100        ciol      30
112233       abc       20
123456       coper      50

向内表:

part_no | qty
123456   10
123456   20
10100    20
112233   15
10100    25

问题表:

part_no | qty
112233   20
112233   15
123456   10
112233   25
10100    40
10100    20

我想要的输出:

part_no | part_name  |inwardQty |issueQty
10100      coil         45     60
112233     abc          15     60
123456     coper        30     10

以下是我写的查询,但没有给出我想要的输出

select s.part_no,s.part_name,sum(i.qty) as inwardQty,sum(p.qty)as issueQty 
from stock s 
left join inward i on s.part_no = i.part_no
left join issue p on s.part_no = p.part_no 
group by 
    s.part_no,s.part_name

通过此查询获得以下输出:

part_no | part_name  |inwardQty |issueQty
10100      coil         90     120
112233     abc          45     60
123456     coper        30     20
4

2 回答 2

4

问题是您将每一行 forinward每一行 for匹配issue,他们正在处理相同的部分。我认为子查询在这里最好:

select s.part_no,s.part_name,i.qty as inwardQty,p.qty as issueQty 
from stock s 
left join
    (select part_no,sum(qty) as qty from inward group by part_no) i on s.part_no = i.part_no
left join
    (select part_no,sum(qty) as qty from issue group by part_no) p on s.part_no = p.part_no 

所以现在,每个连接中只有一个(或零个)行要连接,并且您没有得到笛卡尔积。

于 2012-07-05T06:53:08.793 回答
1

试试这个查询:

SELECT 
    s.part_no, s.part_name,
    InwardQty = (SELECT SUM(qty) FROM @inward i WHERE i.part_no = s.part_no),
    IssueQty = (SELECT SUM(qty) FROM @issue p WHERE p.part_no = s.part_no)
FROM 
    dbo.stock s 
GROUP BY
    s.part_no, s.part_name

给我你想要的输出。

于 2012-07-05T07:10:08.187 回答