--freemarker template
<sqlvars>
<sqlvar name="beginn_semester"><![CDATA[
select param_val from unload_params
where param_id='COSTAGE_start_lv_sem';
]]>
</sqlvar>
</sqlvars>



SELECT 
L.stp_sp_nr,
L.ghk_nr,
L.titel_de,
L.titel_en,
L.nummer,
L.art_name_de,
L.art_name_en,
L.st_sem_nr,
L.org_nr,
L.sws,
L.ects_credits,
L.anerkennungsobjekt_flag,
U.st_studium_nr,
U.st_studstamm_nr,
U.st_studiengang_nr,
null::integer as st_studiengang_nr_msg,
null::varchar(255) as studienidentifikator,
val(S.matrikelnummer) as matrikelnummer,
L.semester
into temp tmp_lv
FROM costage_lehrveranstaltungen L, costage_st_studierendenstammdaten S,
costage_lv_teilnehmende T, costage_st_studien U
where T.stp_sp_nr=L.stp_sp_nr
and U.st_studium_nr=T.st_studium_nr
and U.st_studstamm_nr=S.st_studstamm_nr
and L.semester  >= ${beginn_semester}
 ;

update tmp_lv set studienidentifikator=S.studiengangs_identifikator
from costage_st_studiengaenge S
where S.st_studiengang_nr=tmp_lv.st_studiengang_nr
;
delete from costage_st_lv_aggr
where semester >= ${beginn_semester};

insert into costage_st_lv_aggr(st_studium_nr,
       st_studstamm_nr,
       matrikelnummer,
       semester,
       st_studiengang_nr,
       st_studiengang_nr_msg,
       studienidentifikator,
       stp_sp_nr,
       titel_de,
       nummer,
       art_name_de,
       summe)
select 
       st_studium_nr,
       st_studstamm_nr,
       matrikelnummer,
       semester,
       st_studiengang_nr,
       st_studiengang_nr_msg,
       studienidentifikator,
       stp_sp_nr,
       titel_de,
       nummer,
       art_name_de,
       count(*)
       from tmp_lv
       group by 1,2,3,4,5,6,7,8,9,10,11;

drop table tmp_lv;

