-- Items para clasificacion ABC por sucursal

-- $ for SUC in arm bar bog buc bug cal car iba med mon nei pal pas per vil ric mal mar; do echo $SUC; mysql --defaults-file=/home/sistemas/.my_comercial_odoo.cnf --no-auto-rehash --execute "set @SUC='$SUC'; source ~/sql/2017-02-22-Items_para_ABC_sucursal.sql;" > ~/Agofer_Items_para_ABC_${SUC}.csv; done

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 
	documento_ventas dv
        JOIN documento_ventas_has_item dvi
        ON (dv.id_sucursal = dvi.id_sucursal
                AND dv.id_documento = dvi.id_documento)
	JOIN item i
        USING (id_item)
WHERE
        dv.fecha >= "2021-12-01"
        AND dv.fecha <= "2022-11-30"
	AND dv.id_sucursal = @SUC

GROUP BY 
        Cod

