Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Can PIVOT do this ?
Message
From
18/05/2010 09:18:49
Cetin Basoz
Engineerica Inc.
Izmir, Turkey
 
 
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
01464982
Message ID:
01465000
Views:
53
>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
But think twice, should you do this. Probably there is a better way using apply or Linq.

PS: A linq version (same table as above):
PivotTestTable.AsParallel()
 .GroupBy (pt => pt.RowId )
	.Select (pt => new {
	RowId = pt.Key,
	Column1 = pt.SingleOrDefault (p => p.ColumnId==1).Id,
	Column2 = pt.SingleOrDefault (p => p.ColumnId==2).Id
	})
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
Next
Reply
Map
View

Click here to load this message in the networking platform