Add values in a Select (postgres)

1

I'm having a little problem, I need to populate a gridview in C #, but my query is not doing the sum of some values and this is causing the company code to be repeated and with the value "separated" p>

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

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

    
asked by anonymous 07.06.2018 / 20:06

1 answer

0

You take out lucro of group by, and put that column inside the Sum() function

It 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
    
07.06.2018 / 20:09