ID& SQL Server组动态数据透视/转置属性

时间:2017-12-08 22:01:12

标签: sql sql-server pivot dynamic-sql unpivot

我看到一个动态SQL答案非常类似于我的问题here,但我无法绕过那些让我走到终点线的小变化。

我试图说明为了完成配方而需要前往的所有商店,给出一个表格,其中列出了每种成分的供应商列表。

当前成分表:

RecipeId    Supplier
1           Store A
1           Store B
2           Store A
3           Store B
3           Store C
3           Store D

期望的成分表(在组和枢轴之后):

RecipeId    Supplier 1      Supplier 2      Supplier 3
1           Store A         Store B         NULL
2           Store A         NULL            NULL
3           Store B         Store C         Store D

任何一个配方都可以有零到无限的供应商(如果我绝对需要,我可以将它限制为10) 这是一个更大的查询的一部分,我希望ULTIMATELY将成分表连接回配方表,产生类似于:

RecipeId    Recipe Name     Supplier 1      Supplier 2      Supplier 3      Supplier N
1           Cookies         Store A         Store B         NULL            NULL
2           Cake            Store A         NULL            NULL            NULL
3           Pie             Store B         Store C         Store D         NULL

1 个答案:

答案 0 :(得分:0)

N食谱的简单查询如下:

See working demo

 declare @q varchar(max), @cols varchar(max)
set @cols
     = STUFF((
          SELECT distinct ',' + 
               QUOTENAME('Supplier '+
                         cast(row_number()  over (partition by recipeid order by supplier ) as varchar(max))
                        ) 
            FROM Ingredient
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @q=
'select 
  recipeid,'+ @cols +
' from
(
    select 
       recipeid,
       Supplier, 
       ''Supplier ''+
         cast(row_number()  over (partition by recipeid order by supplier ) as varchar(max))  as r
    from 
       Ingredient 
)I
pivot
( 
    max(Supplier)   
    for r in ('+@cols+')
 )piv'

 exec(@q)