Jes Sie

Jes Sie

  • 739
  • 1.2k
  • 280.2k

Inner Joins, Coalesce and Pivot

Mar 26 2018 10:52 PM
Can someone help me with this error?
  Below is the code:
  1. declare @cols varchar(1000)  
  2. declare @sqls varchar(2000)  
  3.   
  4. select @cols = COALESCE(@cols + ', ','') + QUOTENAME(t.TermCode)  
  5. from tblFinalGradeDetails fg INNER JOIN tblTermMaster t ON fg.TermId = t.TermId   
  6.   
  7. Group by t.TermCode  
  8. SELECT @sqls = 'select *     
  9.       from (    
  10.         select fg.StudentID, fg.StudentName, t.TermCode, fg.FinalGrade     
  11.         from tblFinalGradeDetails fg INNER JOIN tblTermMaster t ON fg.TermId = t.TermId     
  12.         WHERE fg.SchoolCode = ''ISL''     
  13.         and fg.SchoolYear = ''SY201718''     
  14.         ) src      
  15.         PIVOT (    
  16.           sum(fg.FinalGrade)     
  17.           FOR t.TermCode       
  18.           IN (' + @cols + ')) pvt '    
  19. EXEC(@sqls)  
I don't have any problems or issues without the joins but with the joins, I got that error. Thanks so much for any extended help. 

Answers (3)