支点动态列,没有聚合我有调查问卷的数据,SQLServer 2008,我想转到一个矩阵。我看到了几篇关于同一个话题的帖子,但我就是没有兴趣。表如下:Question tableAnswer tableCustomer table各栏:[CustomerID], [QuestionName_1], .., [QuestionName_n] <- 动态问题栏数目)数据:CustomerID, Answer_1, .., Answer_n检索列的代码:DECLARE @columns VARCHAR(8000)SELECT @columns = COALESCE(@columns + ',[' + cast(QuestionName as varchar) + ']',
'[' + cast(QuestionName as varchar)+ ']')FROM Answer A
INNER JOIN Question Q ON A.QuestionID = Q.QuestionIDINNER JOIN Customer C ON A.CustomerID = C.CustomerIDGROUP B
Y Q.QuestionNameSET @columns = '[CustomerID],' + @columnsDECLARE @query VARCHAR(8000)SET @query = 'Some PIVOT query without
aggregation'EXECUTE(@query)最初的查询思想是从带动力柱的枢轴.可以这样做吗?旋转查询会是什么样的呢?PS:我不想使用排名与最大的列数。问候,米歇尔
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
PIVOT
select *from ( select u.userid, u.fname, u.lname, u.mobile, r.question, r.choice from users u left join results r on u.questionid = r.questionid and u.choiceid = r.choiceid) xpivot( min(choice) for question in([are you], [from])) p
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.question) FROM results c FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')set @query = 'SELECT userid, fname, lname, mobile, ' + @cols + ' from ( select u.userid, u.fname, u.lname, u.mobile, r.question, r.choice from users u left join results r on u.questionid = r.questionid and u.choiceid = r.choiceid ) x pivot ( min(choice) for question in (' + @cols + ') ) p 'execute(@query)
添加回答
举报
0/150
提交
取消