我为一个专栏' Total'编写了动态数据透视查询。哪个工作正常,但我想在SQL Server中的多个列上创建动态数据透视查询,但如果我在聚合函数中使用多个列,则显示错误。
我对单列的查询就像这样
Declare @S nvarchar(1024)
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 @S = '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
'
print @S
Execute sp_Executesql @S