SELECT s.nom_sed AS `SEDE`,j.des_jor AS `JORNADA`,g.des_gra AS `GRADO`,c.des_cur AS `CURSO`,ROUND(sp.prom,2) AS PROMEDIO,a.ape_per AS `APELLIDOS`,a.nom_per AS `NOMBRES` FROM (
	SELECT id_alu,id_peri,cod_cur,AVG(nota_d) AS prom,COUNT(CASE WHEN nota_d<3 THEN 1 END) AS perd,COUNT(CASE WHEN cod_mat=14 AND nota_d<3 THEN 1 END) AS nota_comp,COUNT(CASE WHEN nota_d<4 THEN 1 END) AS notas_b FROM seg_final sf 
	WHERE sf.id_peri = VAR01 AND sf.cod_mat<>0 
	GROUP BY id_alu,id_peri,cod_cur HAVING prom>=4 AND perd=0 AND nota_comp=0 AND notas_b=0
) sp
INNER JOIN alumno a USING(id_alu)
INNER JOIN curso c USING(cod_cur)
INNER JOIN sede s USING(id_sed)
INNER JOIN jornada j USING(id_jor)
INNER JOIN grado g USING(cod_gra)
WHERE cod_gra<>14 AND id_sed LIKE 'VAR02'
ORDER BY s.nom_sed,j.des_jor,g.ord_gra,c.des_cur,sp.prom DESC,a.ape_per,a.nom_per 