2014-10-27 166 views
0

我有兩個不同的表,每一個代碼項目的數量相關的領域(每個項目的代碼有不同量)減去總計SQL

我要添加的每個項目的代碼量爲每這兩個表,然後得到的差值(減法)

如果我做的:

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()函數的工作correcty,但是當我做減法,結果是不正確的:

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; 

謝謝!

回答

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 
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;