开发者

SQL Server 2008: Pivot column with no aggregate function workaround

Yes I know, this question has been asked MANY times but after reading all the posts I found that there wasn't an answer that fits my need. So, Heres my question. I would like to take a column of values and pivot them into rows of 6 columns.

I want to take this......    And turn it into this.......................
G                            Letter  Date    Code  Ammount   Name       Account 
081278                       G       081278   12   00123535  John Doe   123456
12
00123535
John Doe
123456

I have 110000 values in this one column in one table called TempTable. I need all the values displayed because each row is an entity to itself. For instance, There is one unique entry for all of the Letter, Date, Code, Ammount, Name, and Account columns. I understand that the aggregate function is required but is there a workaround that will allow me to开发者_如何学Python get this desired result?


Just use a MAX aggregate

If one row = one column (per group of 6 rows) then MAX of a single value = that row value.

However, the data you've posted in insufficient. I don't see anything to:

  • associate the 6 rows per group
  • distinguish whether a row is "Letter" or "Name"

There is no implicit row order or number to rely upon to generate the groups


Unfortunately, the max columns in a SQL 2008 select statement is 4,096 as per MSDN Max Capacity.

Instead of using a pivot, you might consider dynamic SQL to get what you want to do.

Declare @SQLColumns nvarchar(max),@SQL nvarchar(max)
select @SQLColumns=(select '''+ColName+'''',' from TableName for XML Path(''))
set @SQLColumns=left(@SQLColumns,len(@SQLColumns)-1)

set @SQL='Select '+@SQLColumns
exec sp_ExecuteSQL @SQL,N''
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜