Subtraction of 2 sums in sql

0

I have this query

    SELECT  
        t.SI_Articulo,  
        m.SI_Descripcion,  
        t.SI_UM,
        CASE WHEN c.SI_OV IS NOT NULL THEN '*' ELSE NULL END SI_OV,
        (COUNT(DISTINCT t.SI_Ubicacion)) SI_Ubicacion,
        (SUM(DISTINCT t.SI_Existencia)) SI_Existencia,
        (SUM(DISTINCT c.SI_Cantidad)) SI_Cantidad,
        (SUM(DISTINCT c.SI_Cantidad) - SUM(DISTINCT t.SI_Existencia)) SI_DIF 
FROM SI_Inventario_Teorico_QAD t 
INNER JOIN SI_Maestro_Ref_QAD m 
    ON m.SI_Num_Articulo = t.SI_Articulo 
INNER JOIN SI_Conteo c 
    ON c.SI_Num_Articulo = t.SI_Articulo
GROUP BY t.SI_Articulo,  
         m.SI_Descripcion,
         t.SI_UM,  
         c.SI_OV

sample img

The problem I have is that I'm not adding the amount.

    
asked by Eduard 03.07.2017 в 20:04
source

1 answer

3

Ok, first of all, it is not necessary to make that SELECT SUM(...) within the SELECT main, it would suffice to subtract the respective SUM . Anyway, in these cases I always recommend that before doing the JOIN , you have written the group you need to have more clarity of what you are doing. For example, your query would write it like this:

SELECT SI_Cantidad - ISNULL(T.SI_Existencia,0) AS SI_DIF 
FROM (  SELECT  SI_Num_Articulo, 
                SUM(SI_Cantidad) SI_Cantidad
        FROM SI_Conteo
        GROUP BY SI_Num_Articulo) C
LEFT JOIN ( SELECT  SI_Articulo,
                    SUM(SI_Existencia) SI_Existencia
            FROM SI_Inventario_Teorico_QAD
            GROUP BY SI_Articulo) T 
    ON C.SI_Num_Articulo = T.SI_Articulo 
WHERE C.SI_Num_Articulo= 201925
--AND T.SI_Articulo = 201925 -- no hay necesidad de esta condición, es parte del join
;

UPDATED Ok, I'll be honest (and this I say without the intention of offending), but the query that you added to your question is a real disaster. It has many problems, including a DISTINCT unnecessary, a lot of subqueries that are not correct (or that add extra load to the query), a bad selection of columns in GROUP BY , etc. I get the impression that the query you need can be written as follows:

SELECT  t.SI_Articulo,  
        m.SI_Descripcion,  
        t.SI_UM,
        CASE WHEN c.SI_OV IS NOT NULL THEN '*' ELSE NULL END SI_OV,
        COUNT(DISTINCT t.SI_Ubicacion) SI_Ubicacion,
        SUM(t.SI_Existencia) SI_Existencia,
        SUM(c.SI_Cantidad) SI_Cantidad,
        SUM(c.SI_Cantidad) - SUM(t.SI_Existencia) SI_DIF 
FROM SI_Inventario_Teorico_QAD t 
INNER JOIN SI_Maestro_Ref_QAD m 
    ON m.SI_Num_Articulo = t.SI_Articulo 
LEFT JOIN SI_Conteo c 
    ON c.SI_Num_Articulo = t.SI_Articulo
GROUP BY t.SI_Articulo,  
         m.SI_Descripcion,  
         t.SI_UM,
         CASE WHEN c.SI_OV IS NOT NULL THEN '*' ELSE NULL END;
    
answered by 03.07.2017 / 20:10
source