SQL 服务器 - 多行到列的唯一标识符

SQL Server - Multiple rows to columns by unique identifier

我有以下数据库table:

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

我想达到这样的结果:

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

我已经尝试过各种可能性(数据透视表、CTE、临时表)。不幸的是我不明白。我是 SQL.

的新手

一个简单的解决方案是条件聚合(如果您有最大数量的材料)。如果您需要动态,请告诉我。

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

编辑 - 动态枢轴

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);