透视结果返回重复的行

时间:2015-02-12 11:05:38

标签: sql-server-2008 pivot

使用此查询,我得到的结果是空值和重复的ID ...

SELECT QuesId,QuesName,[Ketan Mevada],[Parvej],[Parvez Vahora]  
FROM (
    SELECT tbl_EvolutionAnswer.QuesId,tbl_QuestionMaster.Name as QuesName,
      dbo.Evaluation_Calculation_CourseWise(tbl_EvolutionAnswer.QuesId,34,'Course-Green Course-2045',1065, tbl_EvolutionAnswer.TrainerId ) as Average,
      tbl_EvolutionAnswer.TrainerId,
      tbl_TrainerMaster.Name as TrName  
   from tbl_EvolutionAnswer 
   inner join tbl_TrainerMaster 
      on tbl_EvolutionAnswer.TrainerId = tbl_TrainerMaster.Id 
   inner join tbl_QuestionMaster 
      on tbl_EvolutionAnswer.QuesId = tbl_QuestionMaster.QuestionId 
   where tbl_EvolutionAnswer.EvolId =34 
     and tbl_EvolutionAnswer.TrainerId <> 0 
     and tbl_EvolutionAnswer.CourseId = 'Course-Green Course-2045' 
     and tbl_EvolutionAnswer.SchID = 1065 
) as Books
PIVOT (
    MAX(Average) FOR TrName IN ([Ketan Mevada],[Parvej],[Parvez Vahora])
) as Result

Following images shows result of query..

我需要关注输出

QuesId QuesName                   Ketan Mevada Parvej Parvez Vohra
122    Did your trainer answer... 2            3      2
123    was your trainer activ..   1            4      3

Inner Query Result

1 个答案:

答案 0 :(得分:0)

您的子查询中的列似乎是唯一的,这会导致聚合函数的分组倾斜。当您使用PIVOT函数时,您应该只包括PIVOT和最终选择列表所需的列,否则您将面临最终结果溢出多行的风险。

您需要删除的列似乎是tbl_EvolutionAnswer.TrainerId。进行实际查询:

SELECT QuesId,QuesName,[Ketan Mevada],[Parvej],[Parvez Vahora]  
FROM 
(
    SELECT tbl_EvolutionAnswer.QuesId,
     tbl_QuestionMaster.Name as QuesName,
     dbo.Evaluation_Calculation_CourseWise(tbl_EvolutionAnswer.QuesId,34,'Course-Green Course-2045',1065, tbl_EvolutionAnswer.TrainerId ) as Average,
     tbl_TrainerMaster.Name as TrName  
    from tbl_EvolutionAnswer 
    inner join tbl_TrainerMaster 
      on tbl_EvolutionAnswer.TrainerId = tbl_TrainerMaster.Id 
    inner join tbl_QuestionMaster 
      on tbl_EvolutionAnswer.QuesId = tbl_QuestionMaster.QuestionId  
    where tbl_EvolutionAnswer.EvolId =34 
      and tbl_EvolutionAnswer.TrainerId <> 0 
      and tbl_EvolutionAnswer.CourseId = 'Course-Green Course-2045' 
      and tbl_EvolutionAnswer.SchID = 1065 
) as Books
PIVOT (
    MAX(Average) FOR TrName IN ([Ketan Mevada],[Parvej],[Parvez Vahora])
) as Result