3
I’ve been racking my brain for a few days with SQL on something that should be very simple, but I can’t fix it.
I want to get all data from the table [Numorder] including those not in the table [Itemnotas] with the SQL code below:
SELECT OrdensProducao.NumOrdem AS 'OP'
,OrdensProducao.NomeCliente AS 'Cliente'
,OrdensProducao.Descricao AS 'Descrição'
,OrdensProducao.TipoProduto AS 'Produto'
,NomeAgencia AS 'Agência'
,OrdensProducao.DtEmissao
,SPreco AS 'Valor Fechado'
,SCustosComissoes AS 'Comissão'
,(SPreco - SCustosComissoes - SCustosMat - SCustosTerc - SCustosImpostos - SCustosFin - SCustosVenOutros) AS 'Contr Marginal'
,(SPreco - SCustosComissoes - SCustosMat - SCustosTerc - SCustosImpostos - SCustosFin - SCustosVenOutros - SCustosMO) AS 'Lucro'
,SUM(ItemNota.ValorTotal) AS 'Faturado'
FROM
((OrdensProducao INNER JOIN OrcHdr ON OrdensProducao.NumOrdem = OrcHdr.NumOrcamento)
LEFT OUTER JOIN ItemNota ON OrcHdr.NumOrcamento = ItemNota.NumOrdem)
INNER JOIN NotasFiscais ON ItemNota.ObjID_Nota=NotasFiscais.ObjID
WHERE
(NotasFiscais.NaturezaOperacao IS NULL OR (NOT NotasFiscais.NaturezaOperacao LIKE 'doa*' OR NotasFiscais.NaturezaOperacao LIKE 'reme*')) AND
(ItemNota.Devolucao IS NULL OR ItemNota.Devolucao<> 'D') AND
(NotasFiscais.Situacao IS NULL OR NotasFiscais.Situacao = 'N') AND
(ItemNota.Fatura IS NULL OR ItemNota.Fatura = 'F')
GROUP BY
OrdensProducao.NumOrdem
,OrdensProducao.NomeCliente
,OrdensProducao.Descricao
,OrdensProducao.TipoProduto
,NomeAgencia
,OrdensProducao.DtEmissao
,SPreco
,SCustosComissoes
,(SPreco - SCustosComissoes - SCustosMat - SCustosTerc - SCustosImpostos - SCustosFin - SCustosVenOutros)
,(SPreco - SCustosComissoes - SCustosMat - SCustosTerc - SCustosImpostos - SCustosFin - SCustosVenOutros - SCustosMO)
ORDER BY
OrdensProducao.NumOrdem
But I only get the equivalent data from the two tables! If I remove the [Notasficais] table, it works perfectly, but I need the 'WHERE' dependent on it. I’m pretty sure it’s a relationship thing, but I can’t fix it.
It would not be the case to use LEFT also with Notasfiscais instead of INNER?
– bfavaretto
I’ve tried it too. But it’s not necessary because all the records in Notasfiscais exist in Itensnote
– Cassio Milanelo
Yes, but your query will only bring Itensnote whose NF meets WHERE conditions.
– bfavaretto
Change the order: first the INNER JOINS, then the OUTERS. Never an OUTER and then an INNER. You break the logic of your OUTER.
– rodrigogq
@rodrigogq, could you help me assemble this line in the correct order, please? I’m starting with SQL yet..
– Cassio Milanelo