--摘自百度
PIVOT用于将列值旋转为列名(即行转列),在SQL Server 2000可以用聚合函数配合CASE语句实现
PIVOT的一般语法是:PIVOT(聚合函数(列) FOR 列 in (…) )AS P
完整语法:
table_source
PIVOT(
聚合函数(value_column)
FOR pivot_column
IN(<column_list>)
)
UNPIVOT用于将列明转为列值(即列转行),在SQL Server 2000可以用UNION来实现
完整语法:
table_source
UNPIVOT(
value_column
FOR pivot_column
IN(<column_list>)
)
for instance
[sql]
DECLARE @s NVARCHAR(4000)
SELECT @s = ISNULL(@s + ',', '') + QUOTENAME(QuestionID)
FROM (select distinct QuestionID from #ABC) as A ---列名不要重复
Declare @sql NVARCHAR(4000)
SET @sql='
select r.* from
(select UserID,QuestionID,AnswerID from #ABC) as t
pivot
(
max(t.AnswerID)
for t.QuestionID in ('+@s+')
) as r'
EXEC( @sql)