-- Items para clasificacion ABC

SET NAMES 'utf8';

SELECT 
        i.id_item AS Cod,
        i.descripcion AS Descripcion,
        ROUND(
                SUM(
                        dvi.cantidad * i.peso * (IF(dvi.valor > 0, 1, -1))
                ),
                2
        ) AS Ventas_kg,
	SUM(dvi.valor) AS Ventas_COP,
        COUNT(dv.id_documento) AS numero_facturas,
        COUNT(DISTINCT(EXTRACT(YEAR_MONTH FROM dv.fecha))) AS Frecuencia_meses
FROM 
        item i
        JOIN documento_ventas_has_item dvi
        USING (id_item)
        LEFT JOIN documento_ventas dv
        ON (dv.id_sucursal = dvi.id_sucursal
                AND dv.id_documento = dvi.id_documento)
WHERE
        dv.fecha >= "2021-12-01"
        AND dv.fecha <= "2022-11-30"

GROUP BY 
        Cod

