我有以下数据库表:
| 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 |
我已经尝试了各种可能性(Pivot,CTE,Temp Tables)。不幸的是我没有得到它。我对SQL很新。
答案 0 :(得分:1)
一个简单的解决方案是条件聚合(如果您有最大数量的材料)。如果您需要动态,请告诉我。
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
返回
编辑 - 动态数据透视表
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);