-
Notifications
You must be signed in to change notification settings - Fork 0
/
IndividuTroisMandatsSuccessifs.sql
58 lines (56 loc) · 1.89 KB
/
IndividuTroisMandatsSuccessifs.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
CREATE OR REPLACE FUNCTION "BREF"."IndividuTroisMandatsSuccessifs"(
)
RETURNS TABLE(idindividu character varying)
LANGUAGE 'plpgsql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
declare
rec record;
cmp int;
id_indiv varchar;
type_mandat varchar;
date_fin date;
BEGIN
id_indiv = '';
type_mandat= '';
for rec in
select "IdIndividu", A."TypeMandat", "IdMandat", "DateDebutMandat", "DateFinMandat"
from
(
select "IdIndividu", "TypeMandat", count("IdMandat") as countmandat from "BREF"."Mandat"
join "BREF"."Individu" on "BREF"."Individu"."IdIndividu" = "BREF"."Mandat"."Elu_IdIndividu"
join "BREF"."TypeMandat" on "BREF"."TypeMandat"."IdTypeMandat" = "BREF"."Mandat"."TypeDuMandat_IdTypeMandat"
group by "IdIndividu", "TypeMandat"
having count("IdMandat") = 3 --41387 individus
)A
join "BREF"."Mandat" on "BREF"."Mandat"."Elu_IdIndividu" = A."IdIndividu"
join "BREF"."TypeMandat" on "BREF"."TypeMandat"."TypeMandat" = A."TypeMandat" and "BREF"."Mandat"."TypeDuMandat_IdTypeMandat" = "BREF"."TypeMandat"."IdTypeMandat"
order by "IdIndividu", A."TypeMandat", "DateDebutMandat"
loop
--chaque individu enchaine trois mandats du même type = 3 occurence d'un même individu
if id_indiv != rec."IdIndividu" or type_mandat != rec."TypeMandat" then
id_indiv = rec."IdIndividu";
type_mandat = rec."TypeMandat";
date_fin = rec."DateFinMandat";
cmp = 1; --1° occurence de l'individu
else
if date_fin = rec."DateDebutMandat" or date_fin + 1 = rec."DateDebutMandat" or date_fin + 2 = rec."DateDebutMandat" then --si les mandats s'enchainent
if cmp = 1 then --2° occurence de l'individu
cmp = 2;
elsif cmp = 2 then --3° occurence de l'individu
idindividu := id_indiv;
return next;
cmp = 0;
else
cmp = 0;
end if;
date_fin = rec."DateFinMandat";
else
cmp = 0;
end if;
end if;
end loop;
END;
$BODY$;