2

我有一个表,其中包含会话和问题的数字字段。每节课都有问题 1、2 和 3。1 = “努力”,2 = “满意度”,3 = “知识”。有 5 个可能的答案“非常满意”、“非常满意”、“有点满意”、“不满意”、“非常不满意”。

该表如下所示:

Session  Question  Answer
-------  --------  ------------------
1        1         Unsatisfied
1        2         Very Satisfied
1        3         Somewhat Satisfied

我希望报告看起来像这样:

Session  Effort          Knowledge       Satisfaction
-------  --------------  --------------  --------------
1        Unsatisfied     Unsatisfied     Very Satisfied
2        Very Satisfied  Very Satisfied  Very Satisfied

但是,当我使用我的案例陈述时,我得到:

Session  Question  Effort       Knowledge       Satisfaction
-------  --------  -----------  --------------  ------------
1        1         Unsatisfied  NULL            NULL
1        2         NULL         Very Satisfied  NULL
1        3         NULL         NULL            Unsatisfied

我正在使用的查询是:

select 
    distinct session
    ,Question
    ,case
      when Question = '1' 
      then Answer
            end as "Effort"
,case
      when Question = '3' 
      then Answer
            end as "Knowledge"
,case
      when Question ='2' 
      then Answer
            end as "Satisfaction"
from Survey_Table

关于如何让数据在每个会话中以单行形式返回的任何想法?

4

3 回答 3

4

试试这个将聚合应用于 CASE 语句:

select session
   ,max(case when Question = '1' then Answer end) as Effort
   ,max(case when Question = '3' then Answer end) as Knowledge
   ,max(case when Question ='2' then Answer end) as Satisfaction
from Survey_Table
Group by session

或者您可以使用 PIVOT 功能:

 Select session,
     [1] as effort,
     [2] as satisfaction,
     [3] as knowledge
 From
 (
       Select session, question, answer
       From survey_table
  ) src
  Pivot
  ( 
      Max(answer)
      For question in ([1], [2], [3])
  ) piv
于 2012-12-28T22:16:21.737 回答
0

Also:

You can combine max with partition by to remove the need to group by. e.g.

max(case when xxx ='123' then yyy end) OVER(PARTITION BY a,b,c) AS Test1
于 2014-03-24T13:21:42.807 回答
0

请注意:bluefeet 的回答已经涵盖了这个基本方法。我只是想指出另一种构建PIVOT. 您确实应该有自己的表来将Question列值与标题相关联,但是在没有这样的表的情况下,我会亲自将此信息编码为派生表,而不是[1], [2], [3]使用明确的列别名将 Question 值链接到其相应的标题:

SELECT
   P.*
FROM
   (
      SELECT T.SessionID, Q.Title, T.Answer
      FROM
         dbo.SurveyTable T
         INNER JOIN (
            SELECT 1, 'Effort'
            UNION ALL SELECT 2, 'Knowledge'
            UNION ALL SELECT 3, 'Satisfaction'
         ) Q (Question, Title)
            ON T.Question = Q.Question
   ) S
   PIVOT (Max(Q.Answer) FOR Q.Title IN (Effort, Knowledge, Satisfaction)) P

这将适用于 MS SQL Server 2005 及更高版本。

于 2012-12-28T22:38:54.573 回答