-- Sales per document with credit limit and conditions
-- For PwC

SELECT
        dv.id_cliente AS Customer_Id,
        cs.nombre_cliente AS Customer,
	cs.cupo AS Credit_limit,
	v.nombre_vendedor AS Sales_Rep,
	dv.id_sucursal AS Branch,
	z.descripcion AS City,
	se.descripcion AS Sector,
	SUM(dvi.valor) AS Net_Sales

FROM
        documento_ventas dv
	JOIN documento_ventas_has_item dvi
		USING ( id_documento,id_sucursal )
	LEFT JOIN cliente cl 
		USING ( id_cliente )
	LEFT JOIN cliente_has_sucursal cs
		USING ( id_cliente,id_sucursal )
	LEFT JOIN zona z 
		ON ( cl.id_zona = z.id_zona )
	LEFT JOIN sector se
		ON ( cl.id_sector = se.id_sector )
	LEFT JOIN vendedor v
		ON (dv.id_vendedor = v.id_vendedor
			AND dv.id_sucursal = v.id_sucursal)

WHERE
        (LEFT(dv.id_documento,2) = 'DV' OR
         LEFT(dv.id_documento,2) = 'EF' OR
         LEFT(dv.id_documento,1) = 'F')
	AND dv.fecha >= DATE(CONCAT(YEAR(now())-1,'-10-01'))
	AND dv.fecha <= DATE(CONCAT(YEAR(now()),'-09-30'))
	AND cl.id_cliente > 999

GROUP BY Customer_Id

HAVING Net_Sales > 0
