-- Clientes por sucursal por año sin lineas

SELECT c.id_cliente AS Nit,
    YEAR(dv.fecha) AS Ano,
    dv.id_sucursal AS Sucursal,
    c.nombre_cliente AS Cliente,
    c.id_vendedor AS CodVendedor,
    c.telefono AS Telefono,
    c.direccion AS Direccion,
    z.descripcion AS Ciudad,
    se.id_sector AS CodSector,
    se.descripcion AS Sector,
    sse.id_sector AS CodSubsector,
    sse.descripcion AS Subsector,
    SUM(dvi.valor) AS Valor,
    SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0,1,-1))) AS Peso
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 c
    ON ( dv.id_cliente=c.id_cliente AND dv.id_sucursal=c.id_sucursal )
JOIN sucursal su
    ON ( su.id_sucursal=dv.id_sucursal )
JOIN vendedor v
    ON ( v.id_vendedor=dv.id_vendedor AND dv.id_sucursal=v.id_sucursal )
JOIN sector se
    ON ( se.id_sector=LEFT(c.id_sector,2) )
JOIN subsector sse
    ON ( sse.id_sector=c.id_sector )
JOIN zona z
    ON ( c.id_zona = z.id_zona )

WHERE LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MP]"
    AND NOT (i.tipo LIKE "5")
    AND NOT (dv.id_cliente LIKE "999")
    AND dv.fecha >= '2006-01-01'
    AND dv.fecha <= '2011-08-31'

GROUP BY Nit, Sucursal, Ano

