SELECT
        'sucursal' AS Nivel,
        dv.id_sucursal AS Suc,
        MONTH(dv.fecha) + ((YEAR(dv.fecha)-2011)*12) AS ConsecutivoMes,
        COUNT(DISTINCT dv.id_cliente) AS Clientes,
        SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0,1,-1))) AS Peso,
        SUM(dvi.valor) AS Valor

FROM
        documento_ventas dv
        JOIN documento_ventas_has_item dvi
                ON ( dv.id_documento=dvi.id_documento 
                        AND dv.id_sucursal=dvi.id_sucursal )
        JOIN item i
                ON ( dvi.id_item=i.id_item 
                        AND dvi.id_sucursal=i.id_sucursal )
        JOIN cliente_has_sucursal cs
                ON ( dv.id_sucursal=cs.id_sucursal 
                        AND dv.id_cliente=cs.id_cliente )
        LEFT JOIN linea l
                ON ( LEFT(i.id_linea,2) = l.id_linea )
	JOIN linea_has_subfamilia lhs
		ON (l.id_linea = lhs.id_linea)
        LEFT JOIN solosector se
                ON ( LEFT(cs.id_sector,2) = se.id_sector )
        LEFT JOIN vendedor vdr
                ON ( dv.id_vendedor = vdr.id_vendedor
                        AND dv.id_sucursal = vdr.id_sucursal)

WHERE
    LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MP]" 
    AND (i.tipo != "5")
    AND (dv.id_cliente != "999")
    AND EXTRACT(YEAR_MONTH FROM dv.fecha) = 201205

GROUP BY
        Suc

ORDER BY
        Suc
