Domanda

Right now I have this query:

SELECT 
    Categoria.Descricao AS Categoria,
    Marca.descricao AS Marca,
    Modelo.descricao AS Modelo,Material.n_serie As 'Nº Série', 
    SUM(Entrada.Qtd-COALESCE(Saida.Qtd,0)) AS QTD ,username AS 'User' 
FROM Marca,Modelo,Categoria,Material,Users,Entrada 
    LEFT JOIN Saida ON Entrada.n_serie=Saida.n_serie 
WHERE Marca.id_marca=Modelo.id_marca 
    AND Modelo.categoria= Categoria.id_categoria 
    AND Modelo.id_modelo=Material.id_modelo 
    AND Material.n_serie=Entrada.n_serie 
    AND Entrada.user=Users.id 
GROUP BY Categoria.descricao,Marca.descricao,Modelo.descricao,Material.n_serie;

The output

 Categoria, Marca, Modelo,      Nº Série, QTD,  User
'Cabo',     'UTP', '3 metros', '1234',    '2', 'admin'

As you see, it tells me I have two UTP cables left, when I only have one.

Table Entrada (In):

 n_serie, data_entrada, user, qtd, obs
'1234', '2014-05-12 14:37:34', '6', '50', ''
'1234', '2014-05-12 14:37:43', '6', '2', ''

50 + 2 = 52

Table Saida (Out):

 n_serie, data_saida, user, qtd, obs
'1234', '2014-05-12 14:50:16', '6', '2', ''
'1234', '2014-05-12 14:50:22', '6', '49', ''

49 + 2 = 51

Can somebody tell me where is this query picking up the other one?

Thanks in advance.

È stato utile?

Soluzione

The problem is that you're joining 2 rows against 2 rows and getting 4 rows as a result, then aggregating the 4 rows...

(Each row in Entrada matches with BOTH rows in Saida.)

Entrada:         Saida:

n_serie, qtd     n_serie, qtd        a - b
'1234' , 50      '1234' , 2            48
'1234' , 50      '1234' , 49            1
'1234' , 2       '1234' , 2             0
'1234' , 2       '1234' , 49          -47
                                     -----
                                        2
                                     -----

What you need to do is aggregate each table first, then join them together.

(
  SELECT n_serie, SUM(qtd) AS qtd
    FROM Entrada
GROUP BY n_serie
)
  AS entrada
LEFT JOIN
(
  SELECT n_serie, SUM(qtd) AS qtd
    FROM Saida
GROUP BY n_serie
)
  AS Saida
    ON Saida.n_serie = Entrada.n_serie

Which would give you...

Entrada:         Saida:

n_serie, qtd     n_serie, qtd        a - b
'1234' , 52      '1234' , 51           1
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top