Ver Mensaje Individual
  #4 (permalink)  
Antiguo 05/10/2011, 16:05
Avatar de Libras
Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 18 años, 4 meses
Puntos: 774
Respuesta: consulta de saldos de productos

si tuvieras una fecha seria algo asi



Código SQL:
Ver original
  1. CREATE TABLE #temp(
  2. id INT,
  3. saldo_ini INT,
  4. ingreso INT,
  5. salida INT,
  6. saldo_fin INT,
  7. fecha datetime
  8. )
  9.  
  10. INSERT INTO #temp VALUES (4,0,1240,0,1240,getdate()+1)
  11. INSERT INTO #temp VALUES (4,1240,0,70,1170,getdate()+2)
  12. INSERT INTO #temp VALUES (6,0,39,0,39,getdate()+3)
  13. INSERT INTO #temp VALUES (6,31,0,5,26,getdate()+4)
  14. INSERT INTO #temp VALUES (6,38,0,2,36,getdate()+5)
  15. INSERT INTO #temp VALUES (6,26,0,1,25,getdate()+6)
  16. INSERT INTO #temp VALUES (6,21,0,1,20,getdate()+7)
  17. INSERT INTO #temp VALUES (6,20,0,13,7,getdate()+8)
  18. INSERT INTO #temp VALUES (6,36,0,3,33,getdate()+9)
  19. INSERT INTO #temp VALUES (6,33,0,7,26,getdate()+10)
  20. INSERT INTO #temp VALUES (6,25,0,4,21,getdate()+11)
  21.  
  22.  
  23.  
  24. SELECT t4.id,t4.inicial,t5.ingreso,t5.salida,t4.final,t5.ingreso-t5.salida final_real FROM(
  25. SELECT t3.id,SUM(inicial) inicial , SUM(final) final
  26. FROM(
  27. SELECT
  28. t1.id,
  29. CASE
  30. WHEN fecha=minimo THEN saldo_ini END AS inicial,
  31. CASE
  32. WHEN fecha=maximo THEN saldo_fin END AS final
  33. FROM #temp AS t1
  34. LEFT JOIN (SELECT id, MIN(fecha) AS minimo , MAX(fecha) AS maximo FROM #temp GROUP BY id) AS t2 ON (t1.id=t2.id)
  35. --group by t1.id
  36. ) t3 GROUP BY t3.id) t4
  37. 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!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me