如何将行转移到列

时间:2010-05-25 15:15:42

标签: sql-server sql-server-2005 pivot

在MSSQL中使用PIVOT的每个示例都显示了使用它来聚合数据的人。我试图利用这个只是简单地将行转换为列

例如,考虑以下数据

   SELECT 11826 ID,cast('64 ' as varchar(1000)) as answer,75098 QuestionID,2785 CollectionID  into #temp
insert into #temp SELECT 11827 ID,cast('Security ' as varchar(1000)) as answer,75110 QuestionID,2785 CollectionID 
insert into #temp SELECT 11828 ID,cast('42 ' as varchar(1000)) as answer,75115 QuestionID,2785 CollectionID 
insert into #temp SELECT 11829 ID,cast('3/23/2010 12:01:00 AM ' as varchar(1000)) as answer,75119 QuestionID,2785 CollectionID 
insert into #temp SELECT 11830 ID,cast('3/25/2010 ' as varchar(1000)) as answer,75120 QuestionID,2785 CollectionID 
insert into #temp SELECT 11898 ID,cast('67 ' as varchar(1000)) as answer,75313 QuestionID,2792 CollectionID 
insert into #temp SELECT 11899 ID,cast('True ' as varchar(1000)) as answer,75314 QuestionID,2792 CollectionID 
insert into #temp SELECT 11900 ID,cast('0 ' as varchar(1000)) as answer,75315 QuestionID,2792 CollectionID 
insert into #temp SELECT 11901 ID,cast('adlfkj@alkdfj.com ' as varchar(1000)) as answer,75316 QuestionID,2792 CollectionID

结果应该产生类似

的结果
CollectionID   [AnswerFor75098]     [AnswerFor75110]     [AnswerFor75115]     [AnswerFor75315]...
2785             64                  Security            42                   
2792             Null               Null                 Null                  67

我一直在试验PIVOT,但我不确定这是正确的解决方案。如果是这样,有人提示我可以使用吗? 我想我可以在存储过程中公平地做到这一点,但是,如果可能的话,我试图避免使用游标。

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

人们在尝试PIVOT时通常没有意识到的一件事是,您需要了解您的列并将其硬编码到查询中。这让我们想到,“这真的是最好的方式吗?”

即使您使用Microsoft的PIVOT语法,也无法编写基于数据值动态添加列的通用SQL查询。

PIVOT仍然比编写一堆JOIN更方便,因此我建议使用PIVOT(如果您只使用Microsoft SQL Server)。

答案 1 :(得分:1)

您正在寻找的是交叉表查询。如果你知道你提前寻找的问题编号,你可以这样做:

Select CollectionId
    , Min( Case When Question = 75098 Then Answer End ) As AnswerFor75098
    , Min( Case When Question = 75110 Then Answer End ) As AnswerFor75110
    , Min( Case When Question = 75115 Then Answer End ) As AnswerFor75115
    , Min( Case When Question = 75315 Then Answer End ) As AnswerFor75315
From #Temp
Group By CollectionId

但是,如果你想要的是根据问题动态确定列,那么你想要的是动态交叉表,如果没有一些动态的SQL,就无法在SQL Server中完成。相反,您应该在中间层或报告工具中执行此操作。

答案 2 :(得分:0)

我已经做了一个快速的Sql来展示如何将Pivot与您的示例数据一起使用。 我认为可以改进以实现你想要的东西。

Select CollectionId,[75098],[75110],[75113],[75114],[75115] from
(Select QuestionID ,CollectionId, answer From #temp group by QuestionID,CollectionId, answer) as ST
    PIVOT (count(QuestionID) for QuestionID in ([75098],[75110],[75113],[75114],[75115]))as PT
 group by CollectionId,[75098],[75110],[75113],[75114],[75115] 

@community,请随时建议对此建议进行任何修改