Ver Mensaje Individual
  #2 (permalink)  
Antiguo 20/09/2013, 16:03
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: Consulta con diferentes periodos de tiempo, en uno

Código SQL:
Ver original
  1. CREATE TABLE #temp(
  2. ciudad VARCHAR(20),
  3. turistas INT,
  4. fecha datetime
  5. )
  6.  
  7. INSERT INTO #temp VALUES ('ciudad1',10,'03-10-2013')
  8. INSERT INTO #temp VALUES ('ciudad1',12,'03-10-2013')
  9. INSERT INTO #temp VALUES ('ciudad2',11,'03-10-2013')
  10. INSERT INTO #temp VALUES ('ciudad3',09,'03-10-2013')
  11.  
  12. INSERT INTO #temp VALUES ('ciudad1',01,'03-10-2013')
  13. INSERT INTO #temp VALUES ('ciudad2',08,'03-11-2013')
  14. INSERT INTO #temp VALUES ('ciudad4',15,'03-11-2013')
  15.  
  16. INSERT INTO #temp VALUES ('ciudad1',11,'03-12-2013')
  17. INSERT INTO #temp VALUES ('ciudad2',02,'03-12-2013')
  18. INSERT INTO #temp VALUES ('ciudad3',17,'03-12-2013')
  19. INSERT INTO #temp VALUES ('ciudad5',10,'03-12-2013')
  20.  
  21. --delete from #temp
  22.  
  23. --select datepart(mm,fecha) from #temp
  24. SELECT t1.ciudad,t1.conteoTuristas AS año,t2.conteoturistas AS mes,t3.conteoTuristas AS dia
  25. FROM
  26. (SELECT DISTINCT(ciudad), SUM(turistas) AS conteoTuristas FROM #temp WHERE DATEPART(yy,fecha)=2013 GROUP BY ciudad)t1
  27. LEFT JOIN (SELECT DISTINCT(ciudad), SUM(turistas) AS conteoTuristas FROM #temp WHERE DATEPART(mm,fecha)=3 GROUP BY ciudad) AS t2 ON (t1.ciudad=t2.ciudad)
  28. LEFT JOIN(SELECT DISTINCT(ciudad), SUM(turistas) AS conteoTuristas FROM #temp WHERE fecha='03-10-2013' GROUP BY ciudad) t3 ON (t2.ciudad=t3.ciudad)

Con esto obtienes lo siguiente:

ciudad año mes dia
-------------------- ----------- ----------- -----------
ciudad1 34 34 23
ciudad2 21 21 11
ciudad3 26 26 9
ciudad4 15 15 NULL
ciudad5 10 10 NULL


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