如何联接两个表的行数不相同的表?

时间:2018-07-12 10:19:58

标签: sql sql-server join

我正在尝试为工厂的产品编程...

最主要的是,我想了解原材料的库存量如何,但是有时他们会在完成时带回一些原材料。

因此,我创建了两个视图,一个供库存,它给了我42行,第二个供14行,所以在第三个视图中,我可以将第一个视图的值减去第二个视图的值, 但这行不通,因为它总是给我14行而不是42行。

这是我缺货的第一个视图:

CREATE VIEW V_MOUVEMENT_01(ARTID,plvqe,plvmntht) as
SELECT        P11.ARTID, (SUM(P11.PLDQTE)) AS plvqe, (SUM(P11.PLDMNTNETHT)) AS plvmntht
FROM         dbo.PIECEDIVERSLIGNES AS P11 FULL OUTER JOIN
                         dbo.PIECEDIVERS AS PV ON P11.PCDID = PV.PCDID
WHERE        (PV.PINCODE='STKOUT') AND (PV.DEPID_IN=1) AND (YEAR(PV.PCDDATEEFFET) = YEAR(GETDATE())) AND (MONTH(PV.PCDDATEEFFET) =6)
GROUP BY P11.ARTID

这是可见的库存:

CREATE VIEW V_MOUVEMENT_02(ARTID,plvqe,plvmntht) as
SELECT        P11.ARTID, (SUM(P11.PLDQTE)) AS plvqe, (SUM(P11.PLDMNTNETHT)) AS plvmntht
  FROM  dbo.PIECEDIVERSLIGNES AS P11 FULL OUTER JOIN
                         dbo.PIECEDIVERS AS PV ON P11.PCDID = PV.PCDID
WHERE        (PV.PINCODE='STKIN') AND (PV.DEPID_IN=1) AND (YEAR(PV.PCDDATEEFFET) = YEAR(GETDATE())) AND (MONTH(PV.PCDDATEEFFET) =6)
GROUP BY P11.ARTID

这是决赛,它持续给出14行:

select V1.ARTID , (V1.plvqe-V2.plvqe)FROM V_MOUVEMENT_01 AS V1 
INNER JOIN V_MOUVEMENT_02 AS V2 ON V1.ARTID=V2.ARTID

2 个答案:

答案 0 :(得分:0)

它是INNER JOIN。 改用LEFT OUTER JOIN。

SELECT V1.ARTID, V1.plvqe-ISNULL(V2.plvqe, 0) AS PLVQE
FROM V_MOUVEMENT_01 AS V1 
LEFT OUTER JOIN V_MOUVEMENT_02 AS V2 ON V1.ARTID = V2.ARTID

答案 1 :(得分:0)

我使用了LEFT OUTER JOIN,它对我非常有效....谢谢@ 7schmiede