行到列不能正常工作

时间:2017-07-24 00:55:26

标签: sql sql-server

我正在使用SQL Server 2014,我想要做的是从以下结果:

Answer          QuestionID
Low Effort      1
Satisfied       2
Yes             3
Not Applicable  4
Likely          5
Very patient  and an excellent help. The TV is working fine now thanks again Ria   
Peter   6
Excellent       8

产生类似的东西:

1          |2            |3         |4             ....  |8
Low Effort |Satisfied    |Yes       |Not Applicable....  |Excellent

我正在使用此查询,但无法正常运行:

select 
    '1', '2', '3', '4', '5', '6', '7', '8', '9'
from
    (select 
         Answer, QuestionID
     from 
         [dbo].[SurveyDataDetail]) d
pivot
    (max(Answer)
     for QuestionID in (1, 2, 3, 4, 5, 6, 7, 8, 9)
    ) piv;

有任何意见吗?

1 个答案:

答案 0 :(得分:1)

不要使用单引号。使用转义字符:

select [1], [2], [3], [4], [5], [6], [7], [8], [9]

单引号只能用于字符串和常量。

完整查询将是:

select [1], [2], [3], [4], [5], [6], [7], [8], [9]
from (select Answer, QuestionID
      from [dbo].[SurveyDataDetail]
     ) d
 pivot (
     max(Answer)
     for QuestionID in ([1], [2], [3], [4], [5], [6], [7], [8], [9])
    ) piv;