Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 convert rows to column

Author  Topic 

inbs
Aged Yak Warrior

860 Posts

Posted - 2013-06-03 : 14:01:51
i have this table

Eventkey EventDateKey Filekey
10 1-1-2013 1
20 2-1-2013 1
30 3-1-2013 1
40 4-1-2013 1


i want to get this table

FileKey EventKey_10  Eventkey_20  EventKey_30  EventKey_40
1 1-1-2013 2-1-2013 3-1-2013 4-1-2013

MuMu88
Aged Yak Warrior

549 Posts

Posted - 2013-06-03 : 14:52:34
[CODE]

DECLARE @TEMP2 AS TABLE(EventKey INT, EventDateKey Date, FileKey INT);

INSERT INTO @TEMP2 VALUES(10, '1-1-2013', 1);
INSERT INTO @TEMP2 VALUES(20, '2-1-2013', 1);
INSERT INTO @TEMP2 VALUES(30, '3-1-2013', 1);
INSERT INTO @TEMP2 VALUES(40, '4-1-2013', 1);

SELECT FileKey,
[10] as EventKey_10,
[20] as EventKey_20,
[30] as EventKey_30,
[40] as EventKey_40
FROM (SELECT FileKey, EventDateKey,
EventKey FROM @TEMP2) AS D PIVOT(MAX(EventDateKey) FOR EventKey IN([10], [20], [30], [40])) AS P;
[/CODE]
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-06-03 : 23:56:16
if Eventkey values are not static use

http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -