-- Ventas por sucursal, sector, familia, mes

SELECT
    dv.id_sucursal AS Suc,
    se.descripcion AS Sector,
    MONTH(dv.fecha) AS Mes,
    l.familia AS Familia,
    SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0,1,-1))) AS Peso,
    SUM(dvi.valor) AS Valor,
    SUM(dvi.valor-dvi.costo) AS Utilidad

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 ( i.id_linea = l.id_linea )
    LEFT JOIN solosector se
        ON ( LEFT(cs.id_sector,2) = se.id_sector )

WHERE
    NOT (dv.id_cliente LIKE "999")
    AND YEAR(dv.fecha) = 2011
    AND l.tipo = 1
GROUP BY
    Suc,Sector,Familia,Mes
ORDER BY
    Suc,Sector,Familia,Mes

