如果您不希望提前知道这些值,那么您将需要使用动态SQL。这将创建一个将要执行的SQL字符串,这是必需的,因为在运行查询时必须知道列列表。
该代码将类似于:
DeclARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX), @groupid as intset @groupid = 3select @cols = STUFF((SELECT distinct ',' + QUOTENAME(GroupName) from Columns_Table where groupid = @groupid FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')set @query = 'SELECT ' + @cols + ' from ( SELECT B.GroupName, A.Value , row_number() over(partition by a.ColumnsTableID order by a.Value) seq FROM Values_Table AS A INNER JOIN Columns_Table AS B ON A.ColumnsTableID = B.ID where b.groupid = '+cast(@groupid as varchar(10))+' ) p pivot ( min(P.Value) for P.GroupName in (' + @cols + ') ) p 'execute sp_executesql @query;
请参阅带有演示的SQL Fiddle。对于3的groupid,结果将是:
| KENTROSAURUS | RAPTOR | TREX | TRICERATOPS || whatisthiseven | Itsaraptor | Jurassic | landbeforetime || (null) | zomg | Park | (null) |