想要改变多个枢轴结果

时间:2014-09-03 20:34:39

标签: sql sql-server pivot

我在查询中使用了两个带有union的pivot操作符,我正在获取我想要的数据 但我将第二个数据透视图中的数据作为新行,但我希望这些值作为表中的新列。我得到的数据是这样的:

Name    Ep  ER  FT  SQ       
Amir    2   9   3   2         
muzamil NULL    5   NULL     
roof    2   9   3   7        
Amir    0   9   3   1
muzamil NULL    5   NULL     
roof    2   7   3   7

前三行是第一个枢轴的输出,最后三行是第二个枢轴的输出。但我希望最后三行的值作为前三行的新列。

我希望数据输出如下:

Name    Ep  ER  FT  SQ          JB  CQ   LQ   YC
Amir    2   9   3   2            0   9   3   1
muzamil NULL    5   NULL        NULL 5  NULL NULL
roof    2   9   3   7             2  7   3    7  

使用JB CQ LQ YC作为最后三行的新列,我的数据透视查询是这样的:

Declare @S  nvarchar(1024)
 Declare @Q nvarchar(Max)
set @S=''
Select   @S=@S+a.[Column] +',' from
(SELECT  distinct   ISNULL( dbo.tbSubjects.SubCode,'NoColumnName') as [Column] FROM         dbo.tbAttendance INNER JOIN
                      dbo.tbAttendanceMaster ON dbo.tbAttendance.MasterAID = dbo.tbAttendanceMaster.AtdID INNER JOIN
                      dbo.tbStudent ON dbo.tbAttendance.StID = dbo.tbStudent.StudentID INNER JOIN
                      dbo.tbSubjects ON dbo.tbAttendanceMaster.SubID = dbo.tbSubjects.SubID LEFT OUTER JOIN
                      dbo.tbSemester ON dbo.tbSubjects.SemID = dbo.tbSemester.SemID
                      ) as a

set @S=LEFT(@S,LEN(@S)-1)
 print @S
set @Q='select Name,'+@S+' from (SELECT  distinct tbStudent.Name,   dbo.tbSubjects.SubCode, dbo.fnTotalDays(dbo.tbAttendanceMaster.SubID, 
dbo.tbStudent.StudentID) AS Total 

FROM         dbo.tbAttendance INNER JOIN
                      dbo.tbAttendanceMaster ON dbo.tbAttendance.MasterAID = dbo.tbAttendanceMaster.AtdID INNER JOIN
                      dbo.tbStudent ON dbo.tbAttendance.StID = dbo.tbStudent.StudentID INNER JOIN
                      dbo.tbSubjects ON dbo.tbAttendanceMaster.SubID = dbo.tbSubjects.SubID LEFT OUTER JOIN
                      dbo.tbSemester ON dbo.tbSubjects.SemID = dbo.tbSemester.SemID ) sq
                      pivot(sum(Total)   for SubCode IN('+@S+') ) as pt
 union all
'
set @Q=@Q+'select Name,'+@S+' from (SELECT  distinct tbStudent.Name,   dbo.tbSubjects.SubCode, dbo.fnNoOfDays(dbo.tbAttendanceMaster.SubID, dbo.tbStudent.StudentID) AS Present

FROM         dbo.tbAttendance INNER JOIN
                      dbo.tbAttendanceMaster ON dbo.tbAttendance.MasterAID = dbo.tbAttendanceMaster.AtdID INNER JOIN
                      dbo.tbStudent ON dbo.tbAttendance.StID = dbo.tbStudent.StudentID INNER JOIN
                      dbo.tbSubjects ON dbo.tbAttendanceMaster.SubID = dbo.tbSubjects.SubID LEFT OUTER JOIN
                      dbo.tbSemester ON dbo.tbSubjects.SemID = dbo.tbSemester.SemID ) sq2
                      pivot(sum(Present)   for SubCode IN('+@S+') ) as pt2

'
 Execute sp_Executesql @Q
print @Q

0 个答案:

没有答案