I have a question for setting up a scorecard and that I can not get out of it.
I basically have two tables.
Table 1: CONTRACTS
Fields: Company ID, Contract ID, Product ID, QuantityTable 2: RECEIPTS
Fields: Company ID, Receiving ID, Contract ID, Quantity
With this I mounted this query
SELECT
A.ID_Empresa,
A.ID_Produto,
SUM(CAST(A.Quantidade AS int)) Total
FROM
Contrato A
WHERE
A.Registro='Ativo'
GROUP BY
A.ID_Empresa,
A.ID_Produto
ORDER BY
A.ID_Empresa
This query gives me a correct result.
To try to bring me the result of the total received from the contracts I mounted the following query.
SELECT
A.ID_Empresa,
A.ID_Produto,
SUM(CAST(A.Quantidade AS int)) Total
FROM
Contrato A
LEFT JOIN Recebimentos B ON B.ID_Contrato=A.ID_Contrato
WHERE
A.Registro='Ativo'
GROUP BY
A.ID_Empresa,
A.ID_Produto
ORDER BY
A.ID_Empresa
But when I try to do this join with the RECEIVEDS table to know how much has been received, the query is adding the contract quantity each time it appears on the receiving line.
Is there any way to keep these accounts separate and not duplicate the sum of the contracts?