-- Sales per per line year to year
-- For Board Meeting presentation

SELECT
	EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month,
	l.linea_analisis AS Line,
        ROUND(  
                SUM(dvi.cantidad*i.peso*(IF(dvi.valor>0, 1, -1)))/1000, 2
        ) AS Weight_MT,
        SUM(dvi.valor) AS Value,
        SUM(dvi.costo) AS Cost
FROM
        documento_ventas dv
        JOIN documento_ventas_has_item dvi
                USING ( id_documento,id_sucursal )
        JOIN item i
                USING (id_item)
        JOIN view_lineas l
                USING (id_linea)

WHERE
        LEFT(dv.id_documento,3) RLIKE "E?F[^0-9MPBC]"
        AND NOT (dv.id_cliente LIKE "999")
        AND YEAR(dv.fecha) >= 2015
	
GROUP BY
	Month, Line
