call spQuery_Lista_Matriz_IP(2,NULL,NULL);

DROP PROCEDURE IF EXISTS spQuery_Lista_Matriz_IP;
CREATE PROCEDURE spQuery_Lista_Matriz_IP(
  varArea     int,
  varCodigo   int,
  varNombre   varchar(80)
  )
BEGIN 
  DECLARE varCadAre, varCadCod, varCadNom text default '';
  if ifnull(varArea,'')<>'' then
    set varCadAre = CONCAT(" and M.id_area = ", varArea, " ");
  end if;
  if ifnull(varCodigo,'')<>'' then
    set varCadCod = CONCAT(" and M.id_matriz = ", varCodigo, " ");
  end if;
  if ifnull(varNombre,'')<>'' then
    set varCadNom = CONCAT(" and M.nombre LIKE '%", varNombre, "%' ");
  end if;
  
  set @sql = CONCAT("select A.CMAT, A.MATRIZ, A.ABREV ",
                    "FROM  ",
                    "  ( ",
                    "  select M.id_matriz as CMAT, CONCAT(M.nombre,' - ',M.base) as MATRIZ, M.ABREV ",
                    "  from _sind_matriz M ",
                    "  where M._estado='A' and M.estado='A' ",
                    varCadAre, varCadCod, varCadNom,
                    "  ) A ",
                    "LEFT JOIN ",
                    "  ( ",
                    "  select id_matriz AS CMAT, avg(pormat) AS VERIF ",
                    "  from ",
                    "    ( ",
                    "    select id_matriz, padre, sum(porcentaje) as pormat ",
                    "    from _sind_matriz_detalle ",
                    "    where ifnull(porcentaje,0)<>0 ",
                    "    group by id_matriz, padre ",
                    "    ) X ",
                    "  group by id_matriz ",
                    "  ) B ",
                    "ON A.CMAT = B.CMAT ",	                  
                    "WHERE B.VERIF=100 ",
                    "ORDER BY MATRIZ");	
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;