从两个不同的表SQL中减去总计

时间:2014-10-27 07:39:12

标签: sql sql-server join sum left-join

我有两个不同的表,每个表都有一个与代码项目相关的金额相关字段(每个项目代码有不同的金额)

我想为两个表中的每个表添加每个项目代码的数量,然后得到差异(减法)

如果我这样做:

SELECT codigo,
       ROUND(SUM(importe),2) AS 'resultado' 
FROM tabla1 
GROUP BY codigo

SELECT codigo,
       ROUND(SUM(importe),2) AS 'resultado' 
  FROM tabla2 
GROUP BY codigo

SUM()函数的工作正确,但是当我进行减法时,结果不正确:

SELECT t.codigo,
       ROUND(SUM(t.importe),2) - ROUND(SUM(d.importe),2) AS 'resultado' 
FROM tabla1 t
LEFT JOIN tabla2 d ON t.codigo=d.codigo 
GROUP BY t.codigo;

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试这种方式:

SELECT codigo,
       sum(resultado1 - resultado2) AS 'resultado'
FROM  (       
SELECT codigo,
       ROUND(SUM(importe),2) AS 'resultado1',
       0 AS 'resultado2'
FROM tabla1 
GROUP BY codigo
UNION ALL
SELECT codigo,
       0 AS 'resultado1',
       ROUND(SUM(importe),2) AS 'resultado2'
  FROM tabla2 
GROUP BY codigo
) tablatot
GROUP BY codigo

答案 1 :(得分:0)

SELECT t.codigo,
       ROUND(SUM(ISNULL(t.importe, 0) - ISNULL(D.importe, 0)),2) AS 'resultado' 
FROM tabla1 t
LEFT JOIN tabla2 d ON t.codigo=d.codigo 
GROUP BY t.codigo;