-- Number of invoices per line per year

SELECT
	YEAR(dv.fecha) AS Year,
	l.linea_analisis AS Line,
	IF(
		LEFT(dv.id_documento,1) = 'F',
		'Invoice',
		'Return'
	) AS Type_of_Document,
	COUNT(DISTINCT dv.id_documento) AS Number_of_Documents,
        ROUND(  
                SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
        ) AS Weight_MT,
        SUM(dvi.valor) AS Value

FROM
	documento_ventas dv
	JOIN documento_ventas_has_item dvi
		USING ( id_documento,id_sucursal )
        JOIN item i
                ON ( dvi.id_item = i.id_item
                        AND dvi.id_sucursal = i.id_sucursal )
        JOIN view_lineas l
                ON ( LEFT(i.id_linea,2) = l.id_linea )

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

GROUP BY 
	Year, Line, Type_of_Document

ORDER BY
	Year DESC, Line ASC, Type_of_Document ASC
