si tuvieras una fecha seria algo asi
Código SQL:
Ver originalCREATE TABLE #temp(
id INT,
saldo_ini INT,
ingreso INT,
salida INT,
saldo_fin INT,
fecha datetime
)
INSERT INTO #temp VALUES (4,0,1240,0,1240,getdate()+1)
INSERT INTO #temp VALUES (4,1240,0,70,1170,getdate()+2)
INSERT INTO #temp VALUES (6,0,39,0,39,getdate()+3)
INSERT INTO #temp VALUES (6,31,0,5,26,getdate()+4)
INSERT INTO #temp VALUES (6,38,0,2,36,getdate()+5)
INSERT INTO #temp VALUES (6,26,0,1,25,getdate()+6)
INSERT INTO #temp VALUES (6,21,0,1,20,getdate()+7)
INSERT INTO #temp VALUES (6,20,0,13,7,getdate()+8)
INSERT INTO #temp VALUES (6,36,0,3,33,getdate()+9)
INSERT INTO #temp VALUES (6,33,0,7,26,getdate()+10)
INSERT INTO #temp VALUES (6,25,0,4,21,getdate()+11)
SELECT t4.id,t4.inicial,t5.ingreso,t5.salida,t4.final,t5.ingreso-t5.salida final_real FROM(
SELECT t3.id,SUM(inicial) inicial , SUM(final) final
FROM(
SELECT
t1.id,
CASE
WHEN fecha=minimo THEN saldo_ini END AS inicial,
CASE
WHEN fecha=maximo THEN saldo_fin END AS final
FROM #temp AS t1
LEFT JOIN (SELECT id, MIN(fecha) AS minimo , MAX(fecha) AS maximo FROM #temp GROUP BY id) AS t2 ON (t1.id=t2.id)
--group by t1.id
) t3 GROUP BY t3.id) t4
LEFT JOIN (SELECT t1.id,SUM(ingreso) ingreso , SUM(salida) salida FROM #temp AS t1 GROUP BY t1.id) t5 ON (t4.id=t5.id)
Saludos!