2012/1/12  <[email protected]>:
> Ola Pessoal,
>
> Tenho uma consulta que cliente informa 5 contas de Receitas e 5 de Despesas
> para consultar saldos num periodo:
>
> Preciso que retorne 10 colunas, que serao 5 receitas e 5 despesas;
> na minha consulta abaixo retorna apenas as 5 colunas de Entrada:
> Executanto individualmente retorna corretamente, porem preciso juntar as
> duas.
>
> select
> setor,
> sum(case conta when 4391 then valor else 0 end) as Entrada1,
> sum(case conta when 4454 then valor else 0 end) as Entrada2,
> sum(case conta when 4464 then valor else 0 end) as Entrada3,
> sum(case conta when 6270 then valor else 0 end) as Entrada4,
> sum(case conta when 6262 then valor else 0 end) as Entrada5
> from entradas
> where
> datas between '2009-01-01' and '2009-12-31' and
> setor between 1 and 999
> group by setor
> UNION
> select
> setor,
> sum(case conta when 4979 then valor else 0 end) as Saida1,
> sum(case conta when 5428 then valor else 0 end) as Saida2,
> sum(case conta when 5711 then valor else 0 end) as Saida3,
> sum(case conta when 5960 then valor else 0 end) as Saida4,
> sum(case conta when 6033 then valor else 0 end) as Saida5
> from saidas
> where
> datas between '2009-01-01' and '2009-12-31' and
> setor between 1 and 999
> group by setor
> Como retorno as 1 colunas ?
> Alguem tem alguma dica ?
>


Você não deve utilizar UNION.
Fazendo a união você colocará nas mesmas colunas as Entradai e Saidai.

Para fazer o que deseja faça a junção de seus 2 selects.

select * from
(select
setor,
sum(case conta when 4391 then valor else 0 end) as Entrada1,
sum(case conta when 4454 then valor else 0 end) as Entrada2,
sum(case conta when 4464 then valor else 0 end) as Entrada3,
sum(case conta when 6270 then valor else 0 end) as Entrada4,
sum(case conta when 6262 then valor else 0 end) as Entrada5
from entradas
where
datas between '2009-01-01' and '2009-12-31' and
setor between 1 and 999) foo
FULL OUTER JOIN
(select
setor,
sum(case conta when 4979 then valor else 0 end) as Saida1,
sum(case conta when 5428 then valor else 0 end) as Saida2,
sum(case conta when 5711 then valor else 0 end) as Saida3,
sum(case conta when 5960 then valor else 0 end) as Saida4,
sum(case conta when 6033 then valor else 0 end) as Saida5
from saidas
where
datas between '2009-01-01' and '2009-12-31' and
setor between 1 and 999) bar
ON foo.setor = bar.setor
group by setor;

Osvaldo
_______________________________________________
pgbr-geral mailing list
[email protected]
https://listas.postgresql.org.br/cgi-bin/mailman/listinfo/pgbr-geral

Responder a