当枢轴值是字符串时,适当的枢轴方式

时间:2014-05-19 21:00:37

标签: sql sql-server

我有一个看起来像这样的表:

Person    Answer
Kirk      Captain
Kirk      Iowa
Kirk      Command
Spock     Commander
Spock     Shi Kahr
Spock     Sciences

我试图弄清楚我可以在枢轴中使用哪些聚合来获得这个结果:

Person    Answer 1     Answer 2     Answer 3
Kirk      Captain      Iowa         Command
Spock     Commander    Shi Kahr     Sciences         

我使用Max,但两行都有相同的答案。

原始SQL:

Select * From
(
   Select dView.[respondent code], dView.[Course section], dView.[Subject], 
          dView.Course, dView.[Instructor Name], answers.response, 
          formQuestion.Question_Order
   From Denormalized_V as dView
   Inner Join response_sets as rSets on rSets.sctn_id_code = dView.[section code]
   Inner Join responses as answers on answers.set_id = rSets.set_id
   Inner Join questions as questions on questions.question_id = answers.question_id
   Inner Join form_question as formQuestion on formQuestion.question_id = questions.question_id
   where Term = 'ss14' and 
         [Subject] = 'ws' and 
         Course in ('202') and
         ((@Instructors = '<ALL>') or ([Instructor Pid] = @Instructors or [Instructor Pid] = 'ALL')) and  
         [Course Section] in (@Sections) and [Survey Type] <> 'SOCT'
) t
Pivot (max(response) for question_order in ([1], [2], [3], [4], [5], [6], [7], [8])) as pvt

2 个答案:

答案 0 :(得分:2)

测试数据

DECLARE @TABLE TABLE(Person VARCHAR(20), Answer VARCHAR(20))
INSERT INTO @TABLE VALUES
('Kirk' ,'Captain'),
('Kirk' ,'Iowa'),
('Kirk' ,'Command'),
('Spock','Commander'),
('Spock','Shi Kahr'),
('Spock','Sciences')

<强>查询

SELECT * FROM (
SELECT Person, Answer
      ,'Answer ' + CAST( ROW_NUMBER() OVER (PARTITION BY Person ORDER BY Answer) AS NVARCHAR(10)) Vals
FROM @TABLE)t
 PIVOT (MAX(Answer)
        FOR Vals 
        IN ([Answer 1],[Answer 2],[Answer 3])
        )P

结果集

╔════════╦═══════════╦══════════╦══════════╗
║ Person ║  Answer 1 ║ Answer 2 ║ Answer 3 ║
╠════════╬═══════════╬══════════╬══════════╣
║ Kirk   ║ Captain   ║ Command  ║ Iowa     ║
║ Spock  ║ Commander ║ Sciences ║ Shi Kahr ║
╚════════╩═══════════╩══════════╩══════════╝

答案 1 :(得分:-1)

仔细观察,我看到由于某种原因,我在所有记录上得到了相同的答复代码。我改变了从中获取代码的地方,一切都开始起作用了。