Ver Mensaje Individual
  #7 (permalink)  
Antiguo 16/07/2014, 15:02
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: Dividir valores numericos entre filas

Código SQL:
Ver original
  1. CREATE TABLE #temp(
  2. tipo VARCHAR(20),
  3. dia INT,
  4. cantidad INT
  5. )
  6.  
  7. INSERT INTO #temp VALUES ('AEREO',1,5342)
  8. INSERT INTO #temp VALUES ('AEREO',2,6504)
  9. INSERT INTO #temp VALUES ('AEREO',3,5851)
  10. INSERT INTO #temp VALUES ('AEREO',4,4171)
  11. INSERT INTO #temp VALUES ('FLUVIAL',1,4479)
  12. INSERT INTO #temp VALUES ('FLUVIAL',2,4555)
  13. INSERT INTO #temp VALUES ('FLUVIAL',3,4375)
  14. INSERT INTO #temp VALUES ('FLUVIAL',4,3269)
  15. INSERT INTO #temp VALUES ('TERRESTRE',1,30838)
  16. INSERT INTO #temp VALUES ('TERRESTRE',2,34528)
  17. INSERT INTO #temp VALUES ('TERRESTRE',3,34434)
  18. INSERT INTO #temp VALUES ('TERRESTRE',4,30431)
  19. INSERT INTO #temp VALUES ('TOTAL',1,40659)
  20. INSERT INTO #temp VALUES ('TOTAL',2,45587)
  21. INSERT INTO #temp VALUES ('TOTAL',3,44660)
  22. INSERT INTO #temp VALUES ('TOTAL',4,37871)
  23.  
  24. SELECT
  25. t1.tipo, t1.dia, t1.cantidad / (t2.total * 1.0) AS promedio
  26.  FROM #temp AS t1
  27. LEFT JOIN
  28. (
  29. SELECT SUM(cantidad) total,dia FROM #temp WHERE tipo<>'total' GROUP BY dia
  30. ) AS t2 ON (t1.dia=t2.dia)
  31. WHERE t1.tipo<>'Total'

resultado:

tipo dia promedio
-------------------- ----------- ---------------------------------------
AEREO 1 0.13138542512112
AEREO 2 0.14267225305459
AEREO 3 0.13101209135691
AEREO 4 0.11013704417628
FLUVIAL 1 0.11016011215229
FLUVIAL 2 0.09991883651040
FLUVIAL 3 0.09796238244514
FLUVIAL 4 0.08631934725779
TERRESTRE 1 0.75845446272657
TERRESTRE 2 0.75740891043499
TERRESTRE 3 0.77102552619793
TERRESTRE 4 0.80354360856592
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me

Última edición por Libras; 16/07/2014 a las 15:09