Sql Server row transfer column

Row column select switch SQL Server aggregate functions: http://www.cnblogs.com/wlsandwho/p/4423956.html

- taken from the network

PIVOT for rotating the column value for a column name (i.e., column lines switch), the SQL Server 2000 can be implemented with the CASE statement with aggregate function

PIVOT general syntax is: PIVOT ( aggregate function (column) Column the FOR in (...)) AS P

The complete syntax:

table_source

PIVOT(

Aggregate functions (value_column in)

FOR pivot_column

IN(<column_list>)

)

 

UNPIVOT used to set out into column values ​​(that is, the column switch) in SQL Server 2000 can be used to achieve UNION

The complete syntax:

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 --- Do not repeat the column name 
 
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)
 
 

Reproduced in: https: //www.cnblogs.com/tutuyforever/p/3965979.html

Guess you like

Origin blog.csdn.net/weixin_33938733/article/details/94682061