连接两个数据表后的分组汇总问题
请大虾看看“结存减包装出库”数据为何不对:
SELECT s.代码, s.简化名称,
SUM(s.入库-s.出库) AS 结存
FROM VScdj s
WHERE s.代码= '1304-0200-03-0100 '
GROUP BY s.代码, s.简化名称
SELECT c.代码, m.简化名称,
SUM(c.出库) AS 包装出库
FROM 成品出入库单 c LEFT JOIN 材料代码 m ON (c.代码=m.代码)
WHERE c.工序= '包装 ' AND c.代码= '1304-0200-03-0100 '
GROUP BY c.代码, m.简化名称
SELECT s.代码, s.简化名称,
SUM(s.入库-s.出库)-SUM(c.出库) AS 结存减包装出库
FROM VScdj s INNER JOIN 成品出入库单 c ON (c.代码=s.代码 AND c.工序= '包装 ')
WHERE s.代码= '1304-0200-03-0100 '
GROUP BY s.代码, s.简化名称
(所影响的行数为 1 行)
代码 简化名称 结存
--------------------------
1304-0200-03-0100 AgNi(10)-ASE-W 5058.850
(所影响的行数为 1 行)
代码 简化名称 包装出库
--------------------------
1304-0200-03-0100 AgNi(10)-ASE-W 8419.072
(所影响的行数为 1 行)
代码 简化名称 结存减包装出库
--------------------------
1304-0200-03-0100 AgNi(10)-ASE-W -5282775.106
------解决方案--------------------select s.代码, s.简化名称, sum(s.入库-s.出库) - sum(c.出库) as 结存减包装出库
from VScdj s inner join 成品出入库单 c on s.代码 = c.代码
inner join 材料代码 m on c.代码 = m.代码
where s.代码= '1304-0200-03-0100 ' and c.工序= '包装 '
group by s.代码, s.简化名称
這樣應該行吧
------解决方案----------------------看看這兩個例子,你就容易理解了。
--這個沒有問題,出現的是兩條數據
Select A.* From
(Select 1 As ID) A
Inner Join
(Select 1 As ID
Union All
Select 1
Union All
Select 2) B
On A.Id = B.ID
--但是B中如果也有兩條ID為1的,結果就出現重復了
Select A.* From
(Select 1 As ID
Union All
Select 1) A
Inner Join
(Select 1 As ID
Union All
Select 1
Union All
Select 2) B
On A.Id = B.ID