码迷,mamicode.com
首页 > 其他好文 > 详细

行列转换的例子

时间:2017-06-27 17:04:09      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:span   create   sel   ble   datetime   stp   for   --   exe   

IF OBJECT_ID(tempdb..#ABC) IS NOT NULL  
DROP TABLE #ABC  
  
create table #ABC  
(  
ID  INT  
,UserID BIGINT    
,UserExamID INT   
,TestPaperID INT      
,QuestionID INT  
,AnswerID   INT  
,Ctime DATETIME  
)  
INSERT INTO #ABC  
SELECT 1,120629210042331600,1,3,22,49,GETDATE() UNION ALL  
SELECT 2,120629210042331600,1,3,23,51,GETDATE() UNION ALL  
SELECT 3,120629210042331600,1,3,24,56,GETDATE() UNION ALL  
SELECT 4,120629210042331600,1,3,25,62,GETDATE() UNION ALL  
SELECT 5,120629210042331600,1,3,26,66,GETDATE() UNION ALL  
SELECT 6,120629210042331600,1,3,27,72,GETDATE() UNION ALL  
SELECT 7,120629210042331600,1,3,28,77,GETDATE() UNION ALL  
SELECT 8,120629210042331600,1,3,29,81,GETDATE() UNION ALL  
SELECT 9,120629210042331600,1,3,30,86,GETDATE() UNION ALL  
SELECT 10,120629210042331600,1,3,31,90,GETDATE() UNION ALL  
SELECT 1,120629210011732588,1,3,22,49,GETDATE() UNION ALL  
SELECT 2,120629210011732588,1,3,23,51,GETDATE() UNION ALL  
SELECT 3,120629210011732588,1,3,24,56,GETDATE() UNION ALL  
SELECT 4,120629210011732588,1,3,25,62,GETDATE() UNION ALL  
SELECT 5,120629210011732588,1,3,26,66,GETDATE() UNION ALL  
SELECT 6,120629210011732588,1,3,27,72,GETDATE() UNION ALL  
SELECT 7,120629210011732588,1,3,28,77,GETDATE() UNION ALL  
SELECT 8,120629210011732588,1,3,29,81,GETDATE() UNION ALL  
SELECT 9,120629210011732588,1,3,30,86,GETDATE() UNION ALL  
SELECT 10,120629210011732588,1,3,31,90,GETDATE()    
  
SELECT * FROM #ABC  


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) 

如果要消除NULL,可以利用@s构造一个 ISNULL(字段.0) AS [字段]

 

行列转换的例子

标签:span   create   sel   ble   datetime   stp   for   --   exe   

原文地址:http://www.cnblogs.com/songr/p/7085971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!