-- Sales per item per month for UNO7 years for Fiscalia request
-- Run on old 'comercial' database

SELECT
    DATE_FORMAT(dv.fecha,'%Y%m') AS mes,
    i.id_item AS cod_item,
    i.descripcion AS item,
    SUM(dvi.valor) AS valor,
    SUM(dvi.cantidad * i.peso * (IF(dvi.valor>0,1,-1))) AS peso
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 ) 
WHERE YEAR(dv.fecha) >= 2013
    AND YEAR(dv.fecha) <= 2015
GROUP BY mes, cod_item
