Converting rows to columns SQL Server, T-SQL

被刻印的时光 ゝ 提交于 2019-12-25 08:26:14

问题


I have a function that produces a few rows as string values. The values are as follows:

[12*02]
[12*03]
[12*04]
[12*05]
[12*06]
[12*07]
[12*08]
[12*09]
[12*10]
[12*11]
[12*12]
[12*13]
[12*14]
[12*15]

The values are actually different rows. So [12*01] is row 1 and [12*02] is row # 2 and so on. I want to use these values as column headers. So [12*01] is column 1 and [12*02] is column 2 and so on. I would have used a pivot but this string will keep changing every time and thats the very reason I dont want to use pivots. This is not a college homework assignment, and I have only thought of using RANK and row number functions.

Any help would be appreciated.


回答1:


You will still have to use pivot (or aggregate_function (CASE ) hand-coded variant), but you can do it dynamically. Create a procedure accepting a comma-separated list of column headers and prepare sql code for pivot in varchar variable placing a placeholders where a list should be. This allows you to save pivot code in a table, or read a view definition into varchar variable to help you with syntax checking. After that replace placeholders with actual list and execute pivot.

create proc ExecPivot (@PivotedList nvarchar(max))
as
   set nocount on

   declare @sql nvarchar(max)
   set @sql = N'
       select ColumnList, [PLACEHOLDER]
       from TableA
       pivot 
       (
          min(Value)
          for Key in ([PLACEHOLDER])
       ) a'
   set @sql = REPLACE(@sql, '[PLACEHOLDER]', @PivotedList)
   print @sql
   exec sp_executesql @sql

There is a good reference for concatenating many rows into a single text string. You will probably need it for @PivotedList parameter.

I hope I am not entirely of the mark :-)



来源:https://stackoverflow.com/questions/9812764/converting-rows-to-columns-sql-server-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!