-- Ventas mensuales por linea por documento por cliente
-- Incluye familia, sector, y linea de analisis de Directorio
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,
    dv.id_documento AS Documento,
    LEFT(dv.id_documento,2) AS TipoDocumento,
    MONTH(dv.fecha) + ((YEAR(dv.fecha)-2011)*12) AS ConsecutivoMes,
    l.familia AS Familia,
    l.id_linea_analisis AS CodLinea1,
    l.linea_analisis AS Linea1,
    l.id_linea AS CodLinea2,
    l.descripcion AS Linea2,
    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 )
    LEFT JOIN cliente_has_sucursal cs
        ON ( dv.id_sucursal=cs.id_sucursal 
            AND dv.id_cliente=cs.id_cliente )
    LEFT JOIN view_lineas l
        ON ( LEFT(i.id_linea,2) = 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
    LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MP]" 
    AND (i.tipo != "5")
    AND (dv.id_cliente != "999")
    AND YEAR(dv.fecha) >= 2011

GROUP BY
    Suc,Nit,Documento,CodLinea1,CodLinea2,CodVendedor
ORDER BY
    Suc,Nit,Documento,CodLinea1,CodLinea2,CodVendedor
