This would be a lot easier to work with if there was some sample data and expected results
I've never really had luck when combining the
UNION ALL
with a
GROUP BY
, and generally will break it apart into multiple CTEs.
I would start off with something like this and work with what data you have and what results you expect and the work from there.
; WITH cte1 AS (
SELECT iznos_sa_porezom as 'Duguje'
, '0.00' as 'Potražuje'
, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RN
FROM dbo.mp_ulazni_racun_ostalo_lista
WHERE redni_broj IS NOT NULL
UNION ALL
SELECT iznos_sa_porezom as 'Duguje'
, '0.00' as 'Potražuje'
, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS RN
FROM dbo.mp_ulazni_racun_roba_lista
WHERE redni_broj IS NOT NULL
)
; WITH cte2 AS (
SELECT Duguje, Potražuje, RN
FROM cte1
GROUP BY Duguje
)
SELECT Duguje
, Potražuje
, Saldo = ( SELECT Sum(Duguje-Potražuje)
FROM cte2 t2
WHERE t2.RN <= cte.RN)
FROM cte2