-- Items para clasificacion ABC por sucursal

-- $ for SUC in arm bar bog buc nei bug cal car iba ita per vil pas ric mal mar mon bue pal alf cll val vlc soa cbo san smm cuc; do echo $SUC; mysql --defaults-file=/home/sistemas/.my_comercial_odoo.cnf --no-auto-rehash --execute "set @SUC='$SUC'; source ~/src/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 
        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 >= "2023-02-01"
        AND dv.fecha <= "2024-01-31"
        AND dv.id_sucursal COLLATE utf8_spanish_ci = @SUC COLLATE utf8_spanish_ci

GROUP BY 
        Cod

