数据透视表

时间:2013-11-25 14:54:21

标签: sql sql-server-2008 pivot

我基于我对此回复所做的工作:How to pivot text columns in SQL Server?

我有一张看起来像这样的桌子。

InterviewID | QuestionNumber | PerformanceRatingComments
      1     |       1        |      Text1
      1     |       2        |      Text2
      2     |       1        |      Text3
      2     |       2        |      Text4
      2     |       3        |      Text3
      2     |       4        |      Text4

我想看的是一张显示

的表格
InterviewID | Q1PerfComments | Q2PerfComments | Q3PerfComments | Q4PerfComments.  

我试过这个:

Select InterviewID, 
  pt.[1] as Q1PerfComments, 
  pt.[2] as Q2PerfComments, 
  pt.[3] as Q3PerfComments,
  pt.[4] as Q4PerfComments 
FROM 
(
    select InterviewID, QuestionNumber, PerformanceRatingComments
    from myTable
    WHERE
    PerformanceRatingComments IS NOT NULL
    and QuestionNumber >=1 
    And QuestionNumber <=4
 ) As Temp
PIVOT
(
   max(PerformanceRatingComments)
    FOR QuestionNumber In([1], [2], [3], [4])
) As pt

我收到的错误是:

  

操作数数据类型文本对于max运算符无效。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

根据错误消息:

  

操作数数据类型文本对于max运算符无效。

您无法将聚合函数应用于text数据类型。我的建议是在您收集数据之前将PerformanceRatingComments转换为varchar(max)

Select InterviewID, 
  pt.[1] as Q1PerfComments, 
  pt.[2] as Q2PerfComments, 
  pt.[3] as Q3PerfComments,
  pt.[4] as Q4PerfComments 
FROM 
(
    select InterviewID, QuestionNumber, 
      cast(PerformanceRatingComments as varchar(max)) PerformanceRatingComments
    from myTable
    WHERE PerformanceRatingComments IS NOT NULL
      and QuestionNumber >=1 
      And QuestionNumber <=4
 ) As Temp
PIVOT
(
   max(PerformanceRatingComments)
    FOR QuestionNumber In([1], [2], [3], [4])
) As pt;

请参阅SQL Fiddle with Demo