我在下面的SQL中遇到问题:
mdoc_valor
不能复制或添加,因为它是单个值而不是聚合的一部分,只有mprd_valor
字段应该添加,因为它在子表中。也就是说,modc_valor
字段在父表中,而mprd_valor
字段在子表中。mdoc_valor
字段是根据聚合添加值,我不希望更改此字段。select dpto_codigo,
dpto_descricao,
sum(mdoc_valor) as Liquido,
sum(mprd_valor) as Compras_Bruta
from movdctos
inner join movprodd1017 on (mdoc_transacao=mprd_transacao)
inner join produtos on (prod_codigo=mprd_prod_codigo)
inner join departamentos on (prod_dpto_codigo=dpto_codigo)
where mdoc_datamvto>=CAST('2017-10-31' AS DATE) and
mdoc_datamvto<=CAST('2017-10-31' AS DATE) and
mdoc_dcto_tipo in ('EAQ')
group by
dpto_codigo,
dpto_descricao
根据表名和您的问题,您似乎不需要总结mdoc_valor
字段。我从该字段中删除了聚合,将其添加到GROUP BY并添加了表的别名以提高可读性。
select dpto.dpto_codigo,
dpto.dpto_descricao,
mdoc.mdoc_valor as Liquido,
sum(mprd.mprd_valor) as Compras_Bruta
from movdctos mdoc
inner join movprodd1017 mprd on (mdoc.mdoc_transacao=mprd.mprd_transacao)
inner join produtos prod on (prod.prod_codigo=mprd.mprd_prod_codigo)
inner join departamentos dpto on (prod.prod_dpto_codigo=dpto.dpto_codigo)
where mdoc.mdoc_datamvto>=CAST('2017-10-31' AS DATE) and
mdoc.mdoc_datamvto<=CAST('2017-10-31' AS DATE) and
mdoc.mdoc_dcto_tipo in ('EAQ')
group by
dpto.dpto_codigo,
dpto.dpto_descricao,
mdoc.mdoc_valor;
对于SUM(mprd_valor)
,dpto_codigo
和dpto_descricao
(更名为Liquido)的每个组合,这应该给你mdoc_valor
。