1
I have a question to put together a panel of indicators and I’m not getting out of it.
I basically have two tables.
Table 1: CONTRACTS
Fields: Company ID, Contract ID, Product ID, QuantityTable 2: RECEIPTS
Fields: Company ID, Receipt ID, Contract ID, Quantity
With that I set up 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 set up 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
However, when I try to make this request with the RECEIPTS table to know how much was received, the query is adding up the contract quantity each time it appears on the receiving line.
Is there any way to keep these accounts separate and not double the sum of contracts?
You can write an example of the table data, and an example of the expected result ?
– Rafael Marcos
Yes. In the first query my result is this: ID Company | ID Product | Total 0009 | 0000001 | 11470000 0009 | 0000002 | 800000 0012 | 0000001 | 400000 0017 | 0000001 | 4933540 0017 | 0000002 | 8000000 But with Join it looks like this ID Company | ID Product | Total 0009 | 0000001 | 60090000 0009 | 0000002 | 800000 0012 | 0000001 | 400000 0017 | 0000001 | 62865120 0017 | 0000002 | 8000000
– Mauricio Barcelo da Costa
My answer worked out ?
– Rafael Marcos
Unfortunately not Mark. With its answer the query filtered only the contracts with receipt. I need to keep account of all contracts because I will add the amount received.
– Mauricio Barcelo da Costa
what would be the correct result of the query with Join ?
– Rovann Linhalis