我有3个表格,向内,发行
Stock table的列和数据:
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
答案 0 :(得分:4)
问题在于,您为inward
的每个行匹配行issue
的每个行,为此他们&#39处理相同的部分。我认为子查询在这里最好:
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
现在,每个联接中只有一行(或零)行加入,并且您不会获得笛卡尔积。
答案 1 :(得分: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
给我准确的输出结果。