-- Clientes consolidados por año con ventas y devoluciones

-- Instrucciones de uso:
-- mysql --defaults-file=$HOME/.my_comercial_consultas.cnf < YEARLY-Customers_previous-1_calendar_year.sql > ../Agofer_Customers_per_year_CY$(date +%Y --date="now - 720 days").csv

SELECT c.id_cliente AS Customer_Id,
	c.nombre_cliente AS Customer,
	SUM(dvi.valor) AS Net_Sales

FROM documento_ventas dv
	JOIN documento_ventas_has_item dvi
		USING ( id_documento,id_sucursal )
	LEFT JOIN cliente_has_sucursal c
		USING ( id_cliente,id_sucursal )
	JOIN sucursal su
		USING ( id_sucursal )

WHERE LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MPBC]"
	AND NOT (dv.id_cliente LIKE "999")
	AND YEAR(dv.fecha) = YEAR(now())-2

GROUP BY Customer_Id

-- HAVING Valor > 900000
HAVING LENGTH(Customer_Id) > 3

ORDER BY Net_Sales DESC
