Ver Mensaje Individual
  #2 (permalink)  
Antiguo 14/11/2011, 09:07
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: Sumar valores en base a otra columna

Código SQL:
Ver original
  1. CREATE TABLE #temp(
  2. categoria VARCHAR(20),
  3. marca VARCHAR(10),
  4. sku VARCHAR(5),
  5. volumen INT
  6. )
  7.  
  8.  
  9. INSERT INTO #temp VALUES ('Vinagre', 'Bonna', '0,5', 25)
  10. INSERT INTO #temp VALUES ('Vinagre', 'Bonna', '1', 32)
  11. INSERT INTO #temp VALUES ('Vinagre', 'Casa', '0,5', 47)
  12. INSERT INTO #temp VALUES ('Vinagre', 'Casa', '1', 12)
  13. INSERT INTO #temp VALUES ('Vinagre', 'Casa', '2', 18)
  14. INSERT INTO #temp VALUES ('Vinagre', 'Mazeite', '0,75', 31)
  15. INSERT INTO #temp VALUES ('Vinagre', 'Mazeite', '1', 44)
  16. INSERT INTO #temp VALUES ('Vinagre', 'Mazeite', '2', 20)
  17. INSERT INTO #temp VALUES ('Vinagre', 'Vatel','1', 60)
  18. INSERT INTO #temp VALUES ('Vinagre', 'Vatel','2', 10)
  19.  
  20. SELECT SUM(volumen) AS suma, sku INTO #temp2 FROM #temp GROUP BY sku
  21.  
  22. UPDATE #temp
  23. SET volumen=t1.suma
  24. FROM
  25. (
  26. SELECT suma, sku FROM #temp2
  27. ) AS t1 WHERE #temp.sku=t1.sku
  28.  
  29. SELECT * FROM #temp

Resultado:


categoria marca sku volumen
Vinagre Bonna 0,5 72
Vinagre Bonna 1 148
Vinagre Casa 0,5 72
Vinagre Casa 1 148
Vinagre Casa 2 48
Vinagre Mazeite 0,75 31
Vinagre Mazeite 1 148
Vinagre Mazeite 2 48
Vinagre Vatel 1 148
Vinagre Vatel 2 48


Saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me