0
I have two tables: Venda
and ProdutosVenda
, where the table Venda
has a field named 'Id_key' and the ProdutosVenda
, that will store the products of this sale, has a field called 'Id_referencia', which is the reference of the sale in the products ('Id_referencia' = 'Id_chave').
I happen to be trying to sum up the totals of these products for each sale (ProdutosVenda
) and compare with the total sale itself (Venda
) to look for inconsistencies in the table. However in the code I did I am having the problem of it duplicate the result on the table side Venda
and this does not happen if I make two separate consultations.
Follow my query:
SELECT ProdutosVenda.Id_Referencia, SUM(Venda.TotalVenda),
SUM(ProdutosVenda.Subtotal),
IF(TotalVenda = Subtotal, "Igual", "Diferente")
FROM Venda
LEFT JOIN ProdutosVenda ON Venda.Id_Chave = ProdutosVenda.Id_Referencia
WHERE Venda.DataOperacao = '2017-05-04'
GROUP BY ProdutosVenda.Id_Referencia
Upshot:
Id_Referencia | TotalVenda | Subtotal | Meu IF
00000001.1 | 3400 | 3400 | Igual
00000002.1 | 3399.9 | 3399.9 | Igual
00000003.1 | 4368.64 | 2184.32 | Diferente ***
It turns out that in the result that gave different he doubled the value that would be expected of Totalvenda, that would be 2184.32. Thing that doesn’t happen if I do the individual query for this table.
Obs.: This sale has two products, of 1092.16 each and the other sales that doubled also have more than one product.The ones that gave equal in the consultation have only one product.
It’s probably happening because you have
mais de 1 item em algumas vendas
, then the value oftabela Venda
repeats as the number of records of thetabela ProdutosVenda
. What you could do is make a select with GROUP BY or DISTINCT summing up the items, and a select also with GROUP BY or DISTINCT in the sales table, and make a UNION in both, so would have the values1 para 1
.– rbz
I tried to do like you told me but it seems that only returns me the result of the first select and I need to appear the two results on the screen to check if there is a difference.
– Victor Mendonça
I will post an example in the answer.
– rbz