为了避免“如果指定了SELECT DISTINCT,ORDER BY项必须出现在选择列表中。”,我需要将AssessmentSuperSet.Deadline添加到顶部的SELECT语句中。我应该在哪里这样做?任何帮助非常感谢。感谢。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF(
(SELECT distinct ',' + QUOTENAME(AssessmentSuperSet.Title)
from AssessmentSuperSet inner join AssessmentSet on AssessmentSuperSet.SuperSetID = AssessmentSet.SuperSetID
where ClassID = '8KF/En 14/15' order by AssessmentSuperSet.Deadline ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT StudentID, FName, SName, ' + @cols + ' from
(
select KS3Assessments.StudentID,
Pupils.FName,
Pupils.SName,
KS3Assessments.NCLevel,
AssessmentSuperSet.Title
from KS3Assessments inner join Pupils on KS3Assessments.StudentID = Pupils.StudentID
inner join AssessmentSuperSet on KS3Assessments.SuperSetID = AssessmentSuperSet.SuperSetID
where Pupils.GroupDesignation = ''8KF/En 14/15''
) x
pivot (max(NCLevel) for Title in (' + @cols + ') ) p '
execute(@query)
答案 0 :(得分:1)
使用group by子句代替不同的尝试:
select @cols = STUFF(
(SELECT ',' + QUOTENAME(AssessmentSuperSet.Title)
from AssessmentSuperSet inner join AssessmentSet on AssessmentSuperSet.SuperSetID = AssessmentSet.SuperSetID
where ClassID = '8KF/En 14/15'
group by AssessmentSuperSet.title, AssessmentSuperSet.Deadline
order by AssessmentSuperSet.Deadline ASC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT StudentID, FName, SName, ' + @cols + ' from
(
select KS3Assessments.StudentID,
Pupils.FName,
Pupils.SName,
KS3Assessments.NCLevel,
AssessmentSuperSet.Title
from KS3Assessments inner join Pupils on KS3Assessments.StudentID = Pupils.StudentID
inner join AssessmentSuperSet on KS3Assessments.SuperSetID = AssessmentSuperSet.SuperSetID
where Pupils.GroupDesignation = ''8KF/En 14/15''
) x
pivot (max(NCLevel) for Title in (' + @cols + ') ) p '
execute(@query)
由于您没有提供任何合适的测试数据,我还没有尝试过。