Ver Mensaje Individual
  #2 (permalink)  
Antiguo 24/09/2014, 07:48
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: crear tabla dinamica con cursor o similar

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. campo VARCHAR(25)
  4. )
  5.  
  6. INSERT INTO #temp VALUES ('procesado')
  7. INSERT INTO #temp VALUES ('procesado')
  8. INSERT INTO #temp VALUES ('procesado')
  9. INSERT INTO #temp VALUES ('procesado')
  10. INSERT INTO #temp VALUES ('cerrado')
  11. INSERT INTO #temp VALUES ('cerrado')
  12. INSERT INTO #temp VALUES ('argentina')
  13. INSERT INTO #temp VALUES ('argentina')
  14. INSERT INTO #temp VALUES ('argentina')
  15. INSERT INTO #temp VALUES ('brasil')
  16. INSERT INTO #temp VALUES ('brasil')
  17. INSERT INTO #temp VALUES ('brasil')
  18. INSERT INTO #temp VALUES ('brasil')
  19. INSERT INTO #temp VALUES ('brasil')
  20. INSERT INTO #temp VALUES ('españa')
  21. INSERT INTO #temp VALUES ('españa')
  22. INSERT INTO #temp VALUES ('españa')
  23. INSERT INTO #temp VALUES ('españa')
  24. INSERT INTO #temp VALUES ('mexico')
  25.  
  26.  
  27. DROP TABLE #temp2
  28. SELECT DISTINCT campo, IDENTITY(INT,1,1) AS rn INTO #temp2 FROM #temp
  29.  
  30. DECLARE @x INT
  31. DECLARE @valor VARCHAR(200)
  32. DECLARE @query nvarchar(MAX)
  33. DECLARE @query2 nvarchar(MAX)
  34. DECLARE @query3 nvarchar(MAX)
  35. SET @x=1
  36. SET @query='select '
  37. SET @query2='select '
  38. while @x<=(SELECT COUNT(*) FROM #temp2)
  39. BEGIN
  40.     SELECT @valor=campo FROM #temp2 WHERE rn=@x
  41.     SET @query2=@query2 + 'sum(' + @valor + ') as ' + @valor + ','
  42.     SET @query=@query + 'case when campo=' + CHAR(39) + @valor + CHAR(39) + ' then sum(1) end as ' + @valor + ', ' + CHAR(13)
  43.    
  44.     SET @x=@x+1
  45. END
  46. SET @query=SUBSTRING(@query,1,len(@query)-3)
  47. SET @query=@query + ' from #temp group by campo'
  48. SET @query2=SUBSTRING(@query2,1,len(@query2)-1)
  49.  
  50. SET @query2=@query2 + ' from (' + CHAR(13) + @query + ') as t1'
  51. EXEC sp_executesql @query2

algo como eso :)
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me