0

I have the following database table:

|  Article   |   Material  |
|------------|-------------|
| article001 | material001 |
| article001 | material002 |
| article002 | material002 |
| article002 | material003 |
| article002 | material004 |
| article003 | material002 |
| article004 | material003 |
| article004 | material004 |
| article004 | material005 |
| article004 | material006 |

I want to achive a result like this:

|  Article   |  Material1  |  Material2  |  Material3  |  Material4  |
|------------|-------------|-------------|-------------|-------------|
| article001 | material001 | material002 |             |             |
| article002 | material002 | material003 | material004 |             |
| article003 | material002 |             |             |             |
| article004 | material003 | material004 | material005 | material006 |

I have already tried various possibilities (Pivot, CTE, Temp Tables). Unfortunately I do not get it. I'm pretty new to SQL.

Hellenbeck
  • 47
  • 3

1 Answers1

1

A simple solution is a conditional aggregation (if you have a max number of materials). Let me know if you need to dynamic.

Select Article
      ,Material1 = max(case when RN=1 then Material else '' end)
      ,Material2 = max(case when RN=2 then Material else '' end)
      ,Material3 = max(case when RN=3 then Material else '' end)
      ,Material4 = max(case when RN=4 then Material else '' end)
 From (
        Select *
              ,RN = Row_Number() over (Partition By Article Order by Material)
         From  YourTable
      ) A
 Group By Article

Returns

enter image description here

EDIT - Dynamic Pivot

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName('Material'+cast(RN as varchar(25))) From (Select Distinct RN = Row_Number() over (Partition By Article Order by Material) From Yourtable) A  Order by 1 For XML Path('')),1,1,'') 
Select  @SQL = '
Select [Article],' + @SQL + '
From (
        Select Article,Material
              ,Item = ''Material''+cast(Row_Number() over (Partition By Article Order by Material) as varchar(25))
         From  YourTable
     ) A
 Pivot (max(Material) For [Item] in (' + @SQL + ') ) p'
Exec(@SQL);
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66