-- Facturas y devoluciones por año

-- Instrucciones de uso:
-- mysql --defaults-file=$HOME/.my_comercial_consultas.cnf < YEARLY-Invoices_per_fiscal_year.sql > ../Agofer_Invoices_per_year_FY$(date +%Y).csv

SELECT
	su.nombre_sucursal AS Branch,
	EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month,
	COUNT(DISTINCT dv.id_documento) AS Number_of_Documents,
	LEFT(dv.id_documento,1) AS Type_of_Document,
	SUM(dvi.valor) AS Net_Sales

FROM
	documento_ventas dv
	JOIN documento_ventas_has_item dvi
		USING ( id_documento,id_sucursal )
	LEFT JOIN vendedor vdr
		USING ( id_vendedor,id_sucursal )
	LEFT JOIN cliente_has_sucursal c
		USING ( id_cliente,id_sucursal )
	JOIN sucursal su
		USING ( id_sucursal )
	LEFT JOIN sector se
		ON ( se.id_sector=LEFT(c.id_sector,2) )
	LEFT JOIN zona z
		USING ( id_zona )

WHERE 
	    dv.fecha >= DATE('2011-10-01')
	AND dv.fecha <= DATE('2012-09-30')
	AND LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MPBC]"
	AND NOT (dv.id_cliente LIKE "999")
	AND LENGTH(c.id_cliente) > 3

GROUP BY 
	Branch, Month, Type_of_Document

ORDER BY
	Net_Sales DESC
