unpivot - How to stack data with SQL Server -


OK, so I have data with some large numbers of columns, say 400.

  UID, id, id, var1, var2,. . . Var400 1, 23, 4651, 0, 0,. . . 1 2, 47, 8567, 1, 1,. . . 5   

I have this vertical so that it looks like this:

  UID, ID, ID, variable, value1, 23, 4651 var1, 0 1, 23, 4651 var2, 0 . 1, 23, 4651 var400, 1, 2, 47, 8567, variant 1, 2, 47, 8567, ver 2 2. . . 2, 47, 8567, var400 5   

There should be some relatively easy way to do this change. But I can not think of what this is. Anyone have any ideas?

OK, this will work for SQL Server 2005+ You have a stable version of UNPIVOT :

  select UID, ID1 ID2, variable, price (select * from YourTable) T UNPIVOT (value in variable (Var1, var2, .... var400 )) U;   

With a demo of this.

This will work, but you have to write each of your 400 columns. If you do not want to do that (but I recommend that you do), then you can extract the column name first and use the dynamic SQL:

  @sql of NVARCHAR (Max) Select @cols NVARCHAR (Max) Select @cols = STUFF (Select 'DISTINCT', '+ QUOTENAME (Column) from INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME =' YourTable 'and column' Var% ' For XML path ('', type) .Value ('.', 'NVARCHAR (max)'), 1,1, '') Set @sql = 'Select UID, ID1 ID2, variable, value From (YourTable SELECT *) t UNPIVOT (value variable ( '+ @ Cols +')) U; 'Dynamic version with EXEC (@sql)   

.

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -