Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Can PIVOT do this ?
Message
From
18/05/2010 14:02:43
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01464982
Message ID:
01465042
Views:
31
>>>>Thank you! Had to tweak it a little to get it to work with my tables but it works great. I'm still pawing through it to understand the pivot bit though.....
>>>>As a final twist: the data I really want to put into the new table won't be the Id field but another (varbinary) field from the source table. I haven't yet worked out whether the above can be modified to do that ?
>>>
>>>I don't see why not? If you will get stuck, you can post a closer sample of what you need - I can write a dynamic PIVOT for you.
>>
>>Using the same test table as before except:
DECLARE @test TABLE (Id uniqueidentifier default newID(), ColumnId uniqueidentifier, RowId uniqueidentifier, ObjectData varbinary(max))
and the 'cells' in the output table should hold the content of the ObjectData field rather than the Id field......
>
>Is it closer?
>
>
>drop table test50
>DECLARE @col1 uniqueidentifier
>SET @col1 = '4D7CA12C-FC05-40F8-A2DB-83CB71FF82C4'
>DECLARE @col2 uniqueidentifier
>SET @col2 = 'E751DF43-2E16-480D-9C40-34CF139ABDAF'
>DECLARE @row1 uniqueidentifier
>SET @row1 = 'FB37F155-7F52-438E-B6B8-93258F832DAB'
>DECLARE @row2 uniqueidentifier
>SET @row2='EB2ADCEF-0123-4FB9-A0CF-42D4576B42BD'
>
>create TABLE test50 (Id uniqueidentifier default newID(), ColumnId uniqueidentifier, RowId uniqueidentifier, 
>objectdata varbinary(max))
>INSERT test50 ( ColumnId, RowId, objectdata ) VALUES  ( @col1, @row1,cast('dd' as varbinary(max)) )
>INSERT test50 ( ColumnId, RowId,objectdata  ) VALUES  ( @col2, @row1,cast('bb' as varbinary(max)) )
>INSERT test50 ( ColumnId, RowId,objectdata  ) VALUES  ( @col1, @row2,cast('bbb' as varbinary(max)) )
>INSERT test50 ( ColumnId, RowId,objectdata ) VALUES  ( @col2, @row2,cast('bbee' as varbinary(max)))
>
>declare @Cols varchar(max), @SQL nvarchar(max), @ColsWithNames varchar(max)
>
>select @Cols = coalesce(@Cols + ',','') + QUOTENAME(ColumnID), 
>@ColsWithNames = coalesce(@ColsWithNames + ', ','') + QUOTENAME(ColumnID) + ' as Column' + CAST(Row as varchar(10)) 
> from (select CAST(ColumnID as varchar(36)) as ColumnID, 
>ROW_NUMBER() over (order by  CAST(ColumnID as varchar(36))) as Row from test50 group by CAST(ColumnID as varchar(36))) X
>
>--print @Cols
>
>set @SQL = 'select RowID, ' + @ColsWithNames + ' from (select objectdata as ID, cast(ColumnID as varchar(36)) as ColumnID, RowID from test50) src 
>PIVOT (min(ID) FOR ColumnID IN (' + @Cols + ')) pvt'
>
>--print @SQL
>
>execute (@SQL)
Disappearing for a couple of days I'm afraid. I'll try when I get back. Thanks.
Viv
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform