Sum values in a Select (postgres)

Asked

Viewed 624 times

1

I have a small problem, I need to fill a gridView in C#, but my query is not adding up some values and this is causing the company code to be repeated and with the value "separate".

The value I need is the sum of the 3 values of the company code "X", but the values appear separate.

select i.empresa, i.exercicio, 
(case when c.lucrocontabil=0 then c.lucrosimples 
      when c.lucrosimples=0 then c.lucrocontabil end) as lucro
from informessocios i
left join 
(select sum(coalesce(lucrocontabil,0)) as lucrocontabil, sum(coalesce(lucrosimples,0)) as lucrosimples, empresa, exercicio from informessocios where exercicio = 2017 and (lucrocontabil > 0 or lucrosimples > 0) 
group by empresa, exercicio, lucrocontabil, lucrosimples) c on c.empresa=i.empresa and c.exercicio=i.exercicio
where c.exercicio = 2017 
group by i.empresa, i.exercicio, lucro
order by i.empresa

Exemplo do retorno da query

1 answer

0


You take the lucro group by, and places this column inside the function Sum()

Would look like this:

select 
    i.empresa, 
    i.exercicio, 
    Sum(case when c.lucrocontabil=0 then c.lucrosimples else c.lucrocontabil end) as lucro
from informessocios i
left join (
           select 
               sum(coalesce(lucrocontabil,0)) as lucrocontabil, 
               sum(coalesce(lucrosimples,0)) as lucrosimples, 
               empresa, 
               exercicio 
           from informessocios 
           where exercicio = 2017 
           and (lucrocontabil > 0 or lucrosimples > 0) 
group by empresa, exercicio, lucrocontabil, lucrosimples) c on c.empresa=i.empresa and c.exercicio=i.exercicio
where c.exercicio = 2017 
group by i.empresa, i.exercicio
order by i.empresa
  • Rovann, thank you so much for your help, it worked.

  • Check as an answer. If you have questions, go to [Tour]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.