Skip to content

Instantly share code, notes, and snippets.

@jonathanalves
Last active January 29, 2022 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanalves/78c7627bc1ab35175b04b229cc10c01a to your computer and use it in GitHub Desktop.
Save jonathanalves/78c7627bc1ab35175b04b229cc10c01a to your computer and use it in GitHub Desktop.
drop function IF exists count_business_days;
create or replace function count_business_days(start_date date, end_date date)
returns bigint
as $fbd$
select count(d::date) as d
from generate_series(start_date, end_date, '1 day'::interval) d
where extract('dow' from d) not in (0, 6) and
not exists ( select 1 from public.feriado where dia::date = d::date )
$fbd$ language sql;
with prazos as (
select
p.id as protocolo,
pa.cadastro,
pa.id processo,
pa.tipo,
(select max(cadastro) from protocolo_atividade a where a.protocolo_id = p.id and a.cadastro < pa.cadastro and a.tipo in ('AVANCAR', 'VOLTAR', 'CADASTRAR')) anterior
from protocolo_atividade pa
join protocolo p on p.id = pa.protocolo_id
where p.cadastro >= '2020-01-01'
and pa.tipo in ('AVANCAR', 'VOLTAR')
--and p.id = '860aea68-2cc8-4812-8175-b823e26e4a99'
), prazo_calculado as (
select
p.protocolo,
p.cadastro,
p.processo,
p.tipo,
p.anterior,
dates_diff('day', p.anterior::date, p.cadastro::date) dias_corridos,
count_business_days(p.anterior::date, p.cadastro::date) dias_uteis
from prazos p
)
update protocolo_atividade
set dias_corrido = p.dias_corridos, dias_uteis = p.dias_uteis
from prazo_calculado p
where p.processo = protocolo_atividade.id and p.protocolo = protocolo_atividade.protocolo_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment