-- Ventas por sucursal, por item, por mes: 2023-06 a 2023-11
-- cantidad, peso

SELECT
    dv.id_sucursal AS Branch,
    
    i.id_item AS Cod_item,
    i.descripcion AS Item,
    
    EXTRACT(YEAR_MONTH FROM dv.fecha) AS Month,
    
    l.id_linea AS Cod_Subline,
    l.descripcion AS Subline,
    
    ROUND(
        SUM(
            dvi.cantidad * i.peso * (IF(dvi.valor >0, 1 , -1))
        ),
        2
    ) AS Sales_Kg,
    SUM(dvi.valor) AS Sales_COP,
    ROUND(
        SUM(
            dvi.cantidad * (IF(dvi.valor>0, 1, -1))
        ),
        2
    ) AS Sales_UM,
    i.unidad1 AS UM

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  )
            
    LEFT JOIN view_lineas l
        ON ( i.id_linea = l.id_linea )

WHERE
    dv.fecha >= "2023-06-01"
    AND dv.fecha <= "2023-12-31"

GROUP BY
    Branch,Cod_Item,Month

ORDER BY
    Branch,Cod_Item,Month


