1
I have a select to display 4 fields, but a field that is the valor_pago
is from another table, but I cannot use JOIN
otherwise the return of the records conflicts
So I created a Subquery
but my question is: how do I make my amount of SUM(valor_pago)
be grouped by month. I tried to change my subquery
in two ways, without success:
SELECT MONTH(data_pagamento, SUM(valor_pago)
Operand should countaim 1 Columns
And I tried to group with GROUP BY MONTH(data_pagamento)
]
Subquery Returns more than 1 Row
The mistake is, it makes the annual sum and prints in all fields with this code I’m using
SELECT
MONTH(P.data_venda),
SUM(P.vlr_tot_liquido) AS Faturamento,
SUM(P.custo_total) AS Custos,
SUM(P.vlr_tot_liquido) - SUM(P.custo_total) AS Lucro,
(SELECT
SUM(valor_pago)
FROM contapag
WHERE empresa = 1
AND filial = 1
AND data_pagamento BETWEEN '2016-01-01' AND '2016-12-31'
AND valor_pago > 0) AS Despesas
FROM pedido P
LEFT JOIN (SELECT Min(pedido) as formapag_rec,empresa, filial, pedido, plano as formapag_plano FROM formapag
WHERE empresa = 1 AND filial = 1
GROUP BY empresa, filial, pedido) F ON F.empresa = P.empresa and F.filial = P.filial and F.pedido = P.pedido
LEFT JOIN plano on plano.plano = formapag_plano
WHERE P.empresa = 1 AND P.filial = 1 AND data_venda BETWEEN '2016-01-01' AND '2016-12-31' AND P.vlr_tot_liquido > 0 AND P.status = 'FIN' AND (plano.especie <> 'MOV' OR plano.especie is null)
GROUP BY YEAR(P.data_venda), MONTH(P.data_venda)
try using Sqlfiddle and replicate your test environment: http:/sqlfiddle.com/
– Rovann Linhalis