-- Clientes por sucursal por año sin lineas

SELECT c.id_cliente AS Nit,
    dv.id_sucursal AS Sucursal,
    c.nombre_cliente AS Cliente,
    dv.id_vendedor AS CodVendedor,
    vdr.nombre_vendedor AS Vendedor,
    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

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 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 vdr
        ON ( vdr.id_vendedor=dv.id_vendedor 
            AND dv.id_sucursal=vdr.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 (dv.id_cliente LIKE "999")
    AND dv.fecha >= '2011-01-01'
    AND dv.fecha <= '2012-12-31'

GROUP BY Sucursal, Cliente

HAVING Valor > 900000
