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
 General SQL Server Forums
 New to SQL Server Programming
 Grouping Rows into Columns

Author  Topic 

dog2bert
Starting Member

13 Posts

Posted - 2011-11-06 : 18:33:18
I have data like this:

Material TextLang LineNumber Text
1234 EN 1 SomeText1
1234 EN 2 SomeText2
1234 EN 3 SomeText3
1234 EN 4 SomeText4
12 EN 1 SomeText1a
12 EN 2 SomeText2a

and I want it to look like this:

Material TextLine1 TextLine2 TextLine3 TextLine4
1234 SomeText1 SomeText2 SomeText3 SomeText4
12 SomeText1a SomeText2a

Lines of text is variable

malpashaa
Constraint Violating Yak Guru

264 Posts

Posted - 2011-11-06 : 20:08:05
Try this:

SELECT Material,
ISNULL(MAX(CASE WHEN LineNumber = 1 THEN Text END), '') AS TextLine1,
ISNULL(MAX(CASE WHEN LineNumber = 2 THEN Text END), '') AS TextLine2,
ISNULL(MAX(CASE WHEN LineNumber = 3 THEN Text END), '') AS TextLine3,
ISNULL(MAX(CASE WHEN LineNumber = 4 THEN Text END), '') AS TextLine4
FROM TableName
GROUP BY Material
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-07 : 04:11:31
also

SELECT Material,[1] AS TextLine1,[2] AS TextLine2,[3] AS TextLine3,[4] AS TextLine4
FROM Table t
PIVOT (MAX([Text]) FOR LineNumber IN ([1],[2],[3],[4]))p




------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-07 : 04:11:47

if number of lines is not fixed use

http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -