Hi.
I have a query that should bring two columns, one of the columns will return the value of one column, plus the sum of another column respecting the where clause to add the values.
I came to find the result that serves me as follows:
select
a.entcodent as codent,
a.asscodfpg as codfpg,
a.asscodass as codigo,
a.assmatass as matricula,
a.assnomass as nome,
a.asslogema as email,
case a.assnivass when '0' then 'P' when '1' then 'O' END as nivel,
f.fpgrazsoc as fonte_pagadora,
a.asslimcre - coalesce( (select sum(movvalpri) as consumo from car550 inner join car400 on car550.lojcodloj = car400.lojcodloj and car550.entcodent = car400.entcodent and (car400.vintipvin = 1 or car400.lojcodloj = 9020) where car550.entcodent = a.entcodent and car550.asscodass = a.asscodass and car550.mes_vencimento = f.fpgultmes +1 and car550.movestor = '0' and car550.movvalpri < 0) , 0) as limite,
(select sum(movvalpri) as consumo from car550 inner join car400 on car550.lojcodloj = car400.lojcodloj and car550.entcodent = car400.entcodent and car400.vintipvin = 1 where car550.entcodent = a.entcodent and car550.asscodass = a.asscodass and car550.mes_vencimento = f.fpgultmes +1 and car550.movestor = '0' and car550.movvalpri > 0) as consumo,
(a.asslimcre - (select sum(movvalpri) as consumo from car550 inner join car400 on car550.lojcodloj = car400.lojcodloj and car550.entcodent = car400.entcodent and (car400.vintipvin = 1 or car400.lojcodloj = 9020) where car550.entcodent = a.entcodent and car550.asscodass = a.asscodass and car550.mes_vencimento = f.fpgultmes +1 and car550.movestor = '0')) as saldo,
coalesce(
(select max(movdatcom) from car550 where entcodent = a.entcodent and asscodass = a.asscodass),
(select max(liqdatcom) from car10001 where entcodent = a.entcodent and liqcodass = a.asscodass)
) as data_ultima_autorizacao,
f.fpgrazsoc as nomfpg,
coalesce(t.cartao_numero, c.carnumcar) as numeroCartao,
case a.asssitass when '0' then 'L' when '' then 'L' else 'B' END as status
from
car100 as a
inner join fonte_pg as f on f.fpgcodfpg = a.asscodfpg and f.fpgcodent = a.entcodent
left join car500 as c on c.entcodent = a.entcodent and c.asscodass = a.asscodass and a.assultvia = c.carviacar
left join tbz_cartao as t on t.entidade_codigo = a.entcodent and t.associado_codigo = a.asscodass and t.cartao_via = a.assultvia and t.cartao_tipo = '0'
where
f.fpgcodent = a.entcodent and
f.fpgcodfpg = a.asscodfpg
As you can see, in the columns labeled limit, consumption and balance, I have assembled the result according to a clause (using another query).
However, when I look for multiple records, the query becomes somewhat slow. Would anyone have a reading tip for another approach where I can optimize what I need to do?