要获得所需的结果,您将需要使用该
PIVOT函数。
如果您
title提前知道了所有值(),则可以对静态查询进行硬编码:
select *from( select r.Title, f.UserName, f.Value from ReportItems r left join FormValues f on r.FormID = f.FormID and r.FieldID = f.FieldID) srcpivot( max(value) for title in ([First Name], [Last Name], Age)) piv;
但是听起来
titles您想将其变成列的数量未知。如果真是这样,那么您将需要使用动态sql:
DECLARE @cols AS NVARCHAr(MAX), @query AS NVARCHAr(MAX)select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Title) from ReportItems FOR XML PATH(''), TYPE ).value('.', 'NVARCHAr(MAX)') ,1,1,'')set @query = 'SELECt UserName,' + @cols + ' from ( select r.Title, f.UserName, f.Value from ReportItems r left join FormValues f on r.FormID = f.FormID and r.FieldID = f.FieldID ) x pivot ( max(value) for Title in (' + @cols + ') ) p 'execute(@query)
参见带有演示的SQL Fiddle
两者的结果将是:
| USERNAME | FIRST NAME | LAST NAME | AGE |-------------------------------------------| user 1 | Mike | Oscar | 20 || user 2 | Merry | (null) | 23 || user 3 | Alen | Escott | 28 |
如果您有需要的特定信息
SortOrder,并且已将其存储在表中,那么在获取列列表时,将使用以下内容,并将以正确的顺序返回这些列:
select @cols = STUFF((SELECT ',' + QUOTENAME(Title) from ReportItems group by Title, sortorder order by sortorder FOR XML PATH(''), TYPE ).value('.', 'NVARCHAr(MAX)') ,1,1,'')
参见带有演示的SQL Fiddle
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)