Tema: Consulta SQL
Ver Mensaje Individual
  #4 (permalink)  
Antiguo 23/11/2006, 16:48
daniel00
 
Fecha de Ingreso: noviembre-2006
Ubicación: México
Mensajes: 866
Antigüedad: 17 años, 6 meses
Puntos: 8
Que tal.

Usando tablas temporal y mucho Left Joins, es posible obtner el resultado que deseas.

Basandome en los datos que me proporcionaste te tengo lo siguiente:

Código:
-- A la tabla de movimientos la llamare tempMovim.
-- Esta tabla tiene únicamente los registros para el reporte (los que me pasaste)

-- Y solo usaré las fechas que me muestras de ejemplo.

-- Como primer paso creamos una tabla temporal.
-- Que contedra las fechas de los saldos que queremos consultar
create table #tempFechas
(
  IdRow int identity , 
  Fecha datetime 
)

-- Esto se puede hacer con ciclo while y la función dateadd ( como incrementador )
-- desde Fecha Ini hasta Fecha Fin.
-- Para efectos del ejemplo solo pondre las fechas que me muestras 
insert into #tempFechas 
select distinct Fecha  from tempMovim

-- Y agregaré otra más con datos que no existen.
insert into #tempFechas (fecha)
select '20061118'

select * from #tempFechas 

-- Juntamos las entradas en una tabla temporal #Tabla1
select t.fecha as Fecha,ISNULL( sum(Cant1+ cant2), 0 ) as CantidadE
into #tabla1
from #tempFechas  t LEFT OUTER  JOIN tempMovim m ON
	t.Fecha = m.Fecha
where Tipo = 1 OR  Tipo IS NULL
group by t.fecha


-- Juntamos las Salidas  en una tabla temporal #Tabla2
select t.fecha as Fecha,ISNULL( sum(Cant1+ cant2), 0 ) as CantidadS
into #tabla2
from #tempFechas  t LEFT OUTER  JOIN tempMovim m ON
	t.Fecha = m.Fecha
where Tipo = 2 OR  Tipo IS NULL
group by t.fecha


-- Por último cruzamos las entradas y las salidas y Listo!

SELECT t1.Fecha as Fecha, t1.CantidadE - ISNULL(t2.CantidadS,0) as Saldo
FROM #tabla1 t1 left outer join #tabla2 t2 ON
	t1.Fecha = t2.Fecha

-- Los resultados que obtuve son:
Fecha                                                  Saldo       
------------------------------------------------------ ----------- 
2006-11-18 00:00:00.000                                0
2006-11-19 00:00:00.000                                3
2006-11-20 00:00:00.000                                -2
2006-11-21 00:00:00.000                                2

(4 filas afectadas)

Saludos y cualquier duda, aquí se te amplía.