SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 convert rows into column dynamically
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

cjcclee
Starting Member

33 Posts

Posted - 07/15/2013 :  18:11:00  Show Profile  Send cjcclee an AOL message  Reply with Quote
Hi, Dearl all,

I need help on this query. I have table shown as below,
each logID may have multiple types

LOGID Types
1 Value1
1 Value3
2 Value3
2 Value5
3 Value8
4 Value5

I used dynamic SQL using pivot, get the result as below:

LOGID Value1 Value3 Value5 Value8
1 Value1 Value3 null null
2 null Value3 Value5 null
3 null null null Value8
4 null null Value5 null

This is not the format I want, I want it display as following:

LOGID Column1 Columns2 Column3 Column4
1 Value1 Value3 null null
2 Value3 Value5 null null
3 Value8 null null null
4 Value5 null null null


How to do it? Thank you!

MuMu88
Aged Yak Warrior

547 Posts

Posted - 07/15/2013 :  20:27:21  Show Profile  Reply with Quote


; WITH CTE AS 
(SELECT LOGID, Types, ROW_NUMBER() OVER(PARTITION BY LOGID Order by Types) as RN 
	FROM @Temp)
SELECT T1.LOGID, T1.Types as Col1,  T2.Types as Col2
	FROM CTE T1 LEFT JOIN CTE T2 ON T1.LOGID = T2.LOGID and 
		T1.RN = T2.RN-1 where T1.RN = 1;
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52317 Posts

Posted - 07/16/2013 :  02:11:28  Show Profile  Reply with Quote
Answered here

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=186832

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

cjcclee
Starting Member

33 Posts

Posted - 07/16/2013 :  13:08:26  Show Profile  Send cjcclee an AOL message  Reply with Quote
Thank you so much for both of you. It worked perfectly.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52317 Posts

Posted - 07/16/2013 :  13:40:21  Show Profile  Reply with Quote
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.09 seconds. Powered By: Snitz Forums 2000