with t 
as 
((SELECT '0' ordine,
       '2' mtlevel,
       v.cd_int,
       NULL dt_tem,
       v.cd_grm || ' ' || v.cd_int  nr_tem,
       NULL cd_clifor,
       v.ds_referenza_interna ds_descrizione,
       null nr_lotto,
       'E' cd_tipo_movimento,
       NVL(gi.ps_netto, 0) qta,
       NVL(TAB_MOV.ps_movimento_inizioanno, 0)  tqta
  FROM anag_referenze_ext v
  LEFT OUTER JOIN SIGO_INVENTARIO gi
    ON gi.cd_deposito = :CD_DEPOSITO
   AND gi.cd_int = v.cd_int
   AND gi.dt_inventario = TO_CHAR(TO_DATE(:ADATA), 'YYYY') - 1  || '1231'
  LEFT OUTER JOIN (SELECT m.cd_int,
                          SUM(CASE
                                WHEN m.dt_tem >=
                                     TO_CHAR(TO_DATE(:DADATA), 'YYYY') || '0101' AND
                                     m.dt_tem = TO_CHAR(TO_DATE(:DADATA), 'YYYY') || '0101'
                      AND m.dt_tem <= :ADATA
                      AND m.cd_int BETWEEN :DACDINT AND :ACDINT
                      AND r.fl_non_materiale is null
                    GROUP BY m.cd_int) TAB_MOV ON TAB_MOV.cd_int = v.cd_int
WHERE v.cd_int BETWEEN :DACDINT AND :ACDINT
   AND (TAB_MOV.ps_movimento_inizioanno + NVL(gi.ps_netto, 0) != 0 OR
       TAB_MOV.ps_movimento_periodo != 0))
UNION ALL 
(SELECT '1' ORDINE,
       '0' MTLEVEL,
       m.cd_int,
       m.dt_tem,
       m.nr_tem,
       CASE
         WHEN c.fl_cnf = 'N' THEN
          m.cd_causale
         ELSE
          m.cd_clifor
       END cd_clifor,
       RPAD(CASE c.fl_cnf
              WHEN 'C' THEN
               p.DS_PDV
              WHEN 'F' THEN
               f.ds_ragsoc
              WHEN 'N' THEN
               c.ds_causale
              ELSE
               ' '
            END,
            30,
            ' ') ds_descrizione,
            m.nr_lotto,
       c.fl_entrata_uscita cd_tipo_movimento,
       m.ps_movimento + m.ps_variazione QTA,
       CASE
         WHEN c.fl_entrata_uscita = 'E' THEN
          m.ps_movimento + m.ps_variazione
         ELSE
          - (m.ps_movimento + m.ps_variazione)
       END TQTA
  FROM sigo_magmov m
  INNER JOIN or_referenze r
    ON r.cd_int = m.cd_int
  INNER JOIN anag_causali c
    ON m.cd_causale = c.cd_causale
  LEFT OUTER JOIN v_pdv p
    ON p.cd_pdv = m.cd_clifor
  LEFT OUTER JOIN v_fornitori f
    ON f.cd_fornitore = m.cd_clifor
  WHERE m.cd_deposito = :CD_DEPOSITO
   AND m.dt_tem BETWEEN :DADATA AND :ADATA
   AND r.fl_non_materiale is null
   AND m.cd_int BETWEEN :DACDINT AND :ACDINT)
ORDER BY cd_int, ordine, dt_tem, cd_tipo_movimento)

SELECT t.*,
       sum(tqta) OVER(PARTITION BY null 
                      ORDER BY cd_int, ordine, dt_tem, cd_tipo_movimento 
                      rows BETWEEN unbounded preceding AND CURRENT ROW) row_sum
  FROM t
 ORDER BY cd_int, ordine, dt_tem, cd_tipo_movimento