Ver Mensaje Individual
  #2 (permalink)  
Antiguo 02/07/2014, 08:34
Avatar de Libras
Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Calculando el Acumulado

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. codigo VARCHAR(20),
  4. quantity INT,
  5. doc VARCHAR(20)
  6. )
  7.  
  8.  
  9. CREATE TABLE #resultado
  10. (
  11. codigo VARCHAR(20),
  12. quantity INT,
  13. doc VARCHAR(20),
  14. acumulado INT
  15. )
  16.  
  17. INSERT INTO #temp VALUES ('301262519',32,'SUM')
  18. INSERT INTO #temp VALUES ('301262519',52,'SUM')
  19. INSERT INTO #temp VALUES ('301262519',5,'RES')
  20. INSERT INTO #temp VALUES ('301262519',2,'RES')
  21. INSERT INTO #temp VALUES ('301262519',10,'IGU')
  22. INSERT INTO #temp VALUES ('301262519',10,'RES')
  23. INSERT INTO #temp VALUES ('301262519',6,'IGU')
  24. INSERT INTO #temp VALUES ('301262519',6,'IGU')
  25.  
  26.  
  27. SELECT *,ROW_NUMBER() OVER(partition BY codigo ORDER BY codigo) AS rn INTO #temp2 FROM #temp
  28.  
  29. DECLARE @x INT
  30. DECLARE @doc VARCHAR(20)
  31. DECLARE @acumulado INT
  32. DECLARE @cantidad INT
  33.  
  34. SET @x=1
  35. SET @cantidad=0
  36. SET @acumulado=0
  37.  
  38.  
  39. while @x<=(SELECT COUNT(*) FROM #temp2)
  40. BEGIN
  41.     SELECT @doc=doc,@cantidad=quantity FROM #temp2 WHERE rn=@x
  42.     IF(@doc='sum')
  43.         SET @acumulado=@acumulado+@cantidad
  44.     IF(@doc='res')
  45.         SET @acumulado=@acumulado-@cantidad
  46.     IF(@doc='igu')
  47.         SET @acumulado=@acumulado
  48.  
  49.     INSERT INTO #resultado
  50.     SELECT codigo,@cantidad,@doc,@acumulado FROM #temp2 WHERE rn=@x
  51. SET @x=@x+1
  52. END
  53.  
  54. SELECT * FROM #resultado

Como tus datos se restan, se suman y se dejan igual no es tan facil poner todo eso en un solo query por lo que te recomiendo hacer un procedure o funcion donde pongas el codigo que te envio :)
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me