-- Ventas por cliente por familia con sector
-- (Agregar nombre de vendedor y líneas)

SELECT
    dv.id_sucursal AS Suc,
    se.descripcion AS Sector,
    sbse.descripcion AS Subsector,
    cs.id_cliente AS Nit,
    cs.nombre_cliente AS Cliente,
    dv.id_vendedor AS CodVendedor,
    vdr.nombre_vendedor AS Vendedor,
    MONTH(dv.fecha) AS Mes,
    l.id_linea AS CodLinea,
    l.descripcion AS Linea,
    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 )
    LEFT JOIN subsector sbse
        ON ( cs.id_sector = sbse.id_sector )
    LEFT JOIN vendedor vdr
        ON ( dv.id_vendedor = vdr.id_vendedor
            AND dv.id_sucursal = vdr.id_sucursal)

WHERE
    NOT (dv.id_cliente LIKE "999")
    AND YEAR(dv.fecha) = 2011
    AND l.tipo = 1

GROUP BY
    Suc,Nit,Mes,CodLinea,CodVendedor

ORDER BY
    Suc,Nit,Mes,CodLinea,CodVendedor
