call spQuery_Report_AnalCompCob_Ruta(1, NULl, NULL, '2011');

DROP PROCEDURE IF EXISTS spQuery_Report_AnalCompCob_Ruta;
CREATE PROCEDURE spQuery_Report_AnalCompCob_Ruta(
  varEmpresa    int,
  varVendedor   int,
  varProveedor  int,
	varAnio       varchar(4)
)
BEGIN
  DECLARE varCadVen, varCadPro TEXT default '';
  
  if varVendedor is not null then
    set varCadVen = CONCAT(" and V.id_trabajador = ", varVendedor, " ");
  end if;
  
  if varProveedor is not null then
    set varCadPro = CONCAT(" and P.id_proveedor = ", varProveedor, " ");
  end if;
  
  SET @sql = CONCAT("select V.id_empresa as CEMP, E.nombre as EMPRESA, ",
                    "V.id_ruta as CRUT, R.nombre as RUTA, ",
                    "count(distinct case  when month(V.fecha_emision)=1  then V.id_cliente end) as TOT_ENE, ",
                    "count(distinct case  when month(V.fecha_emision)=2  then V.id_cliente end) as TOT_FEB, ",
                    "count(distinct case  when month(V.fecha_emision)=3  then V.id_cliente end) as TOT_MAR, ",
                    "count(distinct case  when month(V.fecha_emision)=4  then V.id_cliente end) as TOT_ABR, ",
                    "count(distinct case  when month(V.fecha_emision)=5  then V.id_cliente end) as TOT_MAY, ",
                    "count(distinct case  when month(V.fecha_emision)=6  then V.id_cliente end) as TOT_JUN, ",
                    "count(distinct case  when month(V.fecha_emision)=7  then V.id_cliente end) as TOT_JUL, ",
                    "count(distinct case  when month(V.fecha_emision)=8  then V.id_cliente end) as TOT_AGO, ",
                    "count(distinct case  when month(V.fecha_emision)=9  then V.id_cliente end) as TOT_SET, ",
                    "count(distinct case  when month(V.fecha_emision)=10 then V.id_cliente end) as TOT_OCT, ",
                    "count(distinct case  when month(V.fecha_emision)=11 then V.id_cliente end) as TOT_NOV, ",
                    "count(distinct case  when month(V.fecha_emision)=12 then V.id_cliente end) as TOT_DIC  "
                    "from _sv_venta_detalle D ",
                    "inner join _sv_venta V    ON D.id_venta = V.id_venta ",
                    "inner join _sv_ruta R     ON V.id_ruta = R.id_ruta ",
                    "inner join _sv_empresa E  ON V.id_empresa = E.id_empresa ",
                    "inner join _sv_producto P ON D.id_producto = P.id_producto ",
                    "where V._estado = 'A' ",
                    "and V.estado   <> 'AN' ",
                    "and V.id_empresa = ", varEmpresa, " ",
                    varCadVen, varCadPro,
                    "and YEAR(V.fecha_emision) = '", varAnio, "' ",
                    "GROUP BY V.id_empresa, E.nombre, V.id_ruta, R.nombre; "); 
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1; 
END;