两个表的计算量不同

时间:2017-10-19 10:22:06

标签: sql-server tsql

我想从两个不同的表中减去。 结果是第三张表。 这是我的查询SQL:

SELECT
     a.ma
    ,a.Ten
    ,a.Dvt
    ,ISNULL(SUM(a.Soluong),0) AS Nhap
    ,ISNULL(SUM(b.Soluong),0) AS Xuat
    ,(ISNULL(SUM(a.Soluong),0)-ISNULL(SUM(b.Soluong),0)) AS ton
    ,a.Batch,a.MaKe 
FROM tbNhap a 
    INNER JOIN tbXuat b ON a.ma=b.ma and a.Batch=b.Batch
GROUP BY
    a.ma
    ,a.Ten
    ,a.Dvt
    ,a.Batch
    ,a.MaKe 
HAVING a.Batch LIKE '3217101711' AND a.ma LIKE '11020000000031'
ORDER BY
     SUBSTRING(CAST(a.Batch AS varchar(10)), 5, 2)
    ,SUBSTRING(CAST(a.Batch AS varchar(10)), 3, 2) ASC;

我想要显示相同的照片。请。

enter image description here

2 个答案:

答案 0 :(得分:0)

我认为您应该更改SUM和ISNULL之间的顺序,否则如果您的总和中只有一个NULL,则总和将为NULL,然后ISNULL将其更改为0. SELECT将如下所示:

 SELECT
      a.ma
     ,a.Ten
     ,a.Dvt
     ,SUM(ISNULL(a.Soluong,0)) AS Nhap
     ,SUM(ISNULL(b.Soluong,0)) AS Xuat
     ,SUM(ISNULL(a.Soluong,0)-ISNULL(b.Soluong,0)) AS ton
     ,a.Batch,a.MaKe 
 FROM tbNhap a 
     INNER JOIN tbXuat b ON a.ma=b.ma and a.Batch=b.Batch
 GROUP BY
     a.ma
     ,a.Ten
     ,a.Dvt
     ,a.Batch
     ,a.MaKe 
 HAVING a.Batch LIKE '3217101711' AND a.ma LIKE '11020000000031'
 ORDER BY
      SUBSTRING(CAST(a.Batch AS varchar(10)), 5, 2)
     ,SUBSTRING(CAST(a.Batch AS varchar(10)), 3, 2) ASC;  

答案 1 :(得分:0)

这会给你你想要的东西:

DECLARE @tbNhap TABLE
(
    [id] INT
   ,[ma] VARCHAR(24)
   ,[Ten] VARCHAR(24)
   ,[Dvt] VARCHAR(2)
   ,[Soluong] INT
   ,[Batch] VARCHAR(12)
   ,[Make] VARCHAR(4)
);

DECLARE @tbXuat TABLE
(
    [id] INT
   ,[ma] VARCHAR(24)
   ,[Ten] VARCHAR(24)
   ,[Dvt] VARCHAR(2)
   ,[Soluong] INT
   ,[Batch] VARCHAR(12)
   ,[Make] VARCHAR(4)
);

INSERT INTO @tbNhap ([id], [ma], [Ten], [Dvt], [Soluong], [Batch], [Make])
VALUES (1, 11020000000031, 'PTZ5S DN', 'PC', 1200, 3714101711, 'Q209')
      ,(1, 11020000000031, 'PTZ5S DN', 'PC', 1000, 3217101711, 'R202')
      ,(1, 11020000000031, 'PTZ5S DN', 'PC', 770, 3217101711, 'C203');

INSERT INTO @tbXuat ([id], [ma], [Ten], [Dvt], [Soluong], [Batch], [Make])
VALUES (1, 11020000000031, 'PTZ5S DN', 'PC', 500, 3217101711, 'R202')
      ,(1, 11020000000031, 'PTZ5S DN', 'PC', 100, 3217101711, 'C203')
      ,(1, 11020000000031, 'PTZ5S DN', 'PC', 350, 3217101711, 'C203');

SELECT a.ma
       ,a.Ten
       ,a.Dvt
       ,SUM(ISNULL(a.Soluong,0)) AS Nhap
       ,MAX(b.Xuat) AS Xuat
       ,SUM(ISNULL(a.Soluong,0))- MAX(b.Xuat) AS ton
       ,a.Batch
       ,a.MaKe 
FROM @tbNhap a 
LEFT JOIN
(
    SELECT ma
          ,Ten
          ,Dvt
          ,Batch
          ,make
          ,SUM(ISNULL(Soluong,0)) AS Xuat
    FROM @tbXuat
    GROUP BY ma
            ,Ten
            ,Dvt
            ,Batch
            ,make
) b
    ON a.ma=b.ma 
    and a.Batch=b.Batch
    and a.Make = b.make
 GROUP BY
     a.ma
     ,a.Ten
     ,a.Dvt
     ,a.Batch
     ,a.MaKe 
 HAVING a.ma LIKE '11020000000031'
  ORDER BY
      SUBSTRING(CAST(a.Batch AS varchar(10)), 5, 2)
     ,SUBSTRING(CAST(a.Batch AS varchar(10)), 3, 2) ASC;