在Postgresql中选择项目SUM Aggregate

问题描述 投票:0回答:1

我在下面的SQL中遇到问题:

  1. 字段mdoc_valor不能复制或添加,因为它是单个值而不是聚合的一部分,只有mprd_valor字段应该添加,因为它在子表中。也就是说,modc_valor字段在父表中,而mprd_valor字段在子表中。
  2. 发生的事情是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
sql postgresql
1个回答
0
投票

根据表名和您的问题,您似乎不需要总结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_codigodpto_descricao(更名为Liquido)的每个组合,这应该给你mdoc_valor

© www.soinside.com 2019 - 2024. All rights reserved.