-- Precio de venta promedio de la lamina HR por kilo, mes a mes en 5 años

SELECT
	EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month,
        SUM(dvi.valor) AS Net_Sales,
        ROUND(  
                SUM(
                        dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
                ),
                2
        ) AS Amount_Kg

FROM
        documento_ventas dv

        JOIN documento_ventas_has_item dvi
                ON ( dv.id_documento = dvi.id_documento
                        AND dv.id_sucursal = dvi.id_sucursal )

        JOIN item i
                ON ( dvi.id_item = i.id_item
                        AND dvi.id_sucursal = i.id_sucursal )
        JOIN linea l
                ON ( l.id_linea = LEFT( i.id_linea, 2 )
                        AND l.tipo = i.tipo )

WHERE

	(l.id_linea = 27 OR l.id_linea = 30 OR l.id_linea = 32)
	AND LEFT(dv.id_documento,2) RLIKE "F|D[^0-9MP]"
        AND NOT (dv.id_cliente LIKE "999")
        AND dv.fecha >= '2008-01-01'


GROUP BY

	Month

ORDER BY

	Month
