Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Can PIVOT do this ?
Message
From
18/05/2010 09:52:56
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01464982
Message ID:
01465010
Views:
39
>>>Given a SQL2008 table structure:
>>>
>>>Id, ColumnId, RowId
>>>1 1 1
>>>2 1 2
>>>3 2 1
>>>4 2 2
>>>
>>>How do I convert it to:
>>>
>>>Row, Column1 Column2
>>> 1 1 3
>>> 2 2 4
>>>
>>>In case it's relevant the values are all GUIDS rather than ints and there will be more columns (and, obviously, rows)
>>>(Sorry about the spacing....)
>>
>>
>>DECLARE @test TABLE (Id uniqueidentifier default newID(), ColumnId int, RowId INT)
>>INSERT @test ( ColumnId, RowId ) VALUES  ( 1,1 )
>>INSERT @test ( ColumnId, RowId ) VALUES  ( 1,2 )
>>INSERT @test ( ColumnId, RowId ) VALUES  ( 2,1 )
>>INSERT @test ( ColumnId, RowId ) VALUES  ( 2,2 )
>>SELECT * FROM @test
>>
>>SELECT RowID, 
>>	cast([1] as uniqueidentifier) as Column1,
>>	cast([2] as uniqueidentifier) as Column2
>>from (select cast(Id AS BINARY(16)) AS id, columnId, rowID FROM @test) tmp
>>pivot 
>>(
>>  max( id )
>>  for columnID in ([1],[2])
>>) AS pvt
>>
>
>I'm don't think it works if ColumnId and RowId are actually uniqueidentifiers to start with....
>Try with this table:
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'
>
>DECLARE @test TABLE (Id uniqueidentifier default newID(), ColumnId uniqueidentifier, RowId uniqueidentifier)
>INSERT @test ( ColumnId, RowId ) VALUES  ( @col1, @row1 )
>INSERT @test ( ColumnId, RowId ) VALUES  ( @col2, @row1 )
>INSERT @test ( ColumnId, RowId ) VALUES  ( @col1, @row2 )
>INSERT @test ( ColumnId, RowId ) VALUES  ( @col2, @row2 )
>
>>But think twice, should you do this. Probably there is a better way using apply or Linq.
>
>In point of fact this will be used via EntityFramework IAC so a Linq query that did the work might in fact be preferable. Any suggestions ?
>
>Viv

Viv,
I have already given a Linq sample in my previous message. Probably we were sending the reply at the same time so you missed the updated message.
Cetin
Çetin Basöz

The way to Go
Flutter - For mobile, web and desktop.
World's most advanced open source relational database.
.Net for foxheads - Blog (main)
FoxSharp - Blog (mirror)
Welcome to FoxyClasses

LinqPad - C#,VB,F#,SQL,eSQL ... scratchpad
Previous
Reply
Map
View

Click here to load this message in the networking platform