简体   繁体   English

SQL Server 2005错误的输出

[英]sql server 2005 wrong output

I have 3 table stock,inward,issue 我有3表库存,里面,有问题

Stock table's columns and data : 库存表的列和数据:

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

inward table : 内向表:

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

issue table : 问题表:

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

my desired output : 我想要的输出:

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

following is the query i have written,but not giving my desired output 以下是我编写的查询,但未提供所需的输出

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

getting following output by this query : 通过此查询获取以下输出:

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

The problem is that you're matching every row for inward with every row for issue , for which they're dealing with the same part. 问题是,你的每一行匹配inward每一行的issue ,他们正在处理相同的一部分,其中。 I think subqueries would be best here: 我认为最好在这里进行子查询:

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 

So now, there's only one (or zero) rows to join in each of the joins, and you don't get a cartesian product. 因此,现在每个联接中只有一(或零)行要联接,并且您没有得到笛卡尔积。

Try this query: 试试这个查询:

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

Gives me exactly your desired output. 给我确切您想要的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM