SQL重复行

时间:2017-04-13 15:06:59

标签: sql-server

这是我的查询,我无法弄清楚为什么每一行都会使结果增加三倍。我试过选择不同的。对于每条记录,AssessmentProficiencyLevelRank重复3次。如何删除这些额外的行?

Select distinct
sai.AcademicYear,
sai.AcademicYearNum,
sai.StateCode,
sai.StudentBKID,
sai.StudentDWID,
sai.LastName,
sai.FirstName,
sai.ReportName,
sai.calendarperiodname,
case when aps.StateAssessmentProficiencySubjectName = 'Not Applicable' and sub.Subject = 'Algebra I' then 'Math' 
     when aps.StateAssessmentProficiencySubjectName = 'Not Applicable' and sub.Subject = 'Algebra 1' then 'Math'
     when aps.StateAssessmentProficiencySubjectName = 'Not Applicable' and sub.Subject = 'Algebra II' then 'Math'
     when aps.StateAssessmentProficiencySubjectName = 'Reading' then 'ELA'
else aps.[StateAssessmentProficiencySubjectName] end as StateAssessmentProficiencySubjectName,
sai.AssessmentName,
sai.assessmentdate,
sai.scaledscore,
sai.GradeAbbreviation,
dar.proficiency,
dar.AssessmentProficiencyLevelRank
into #main

From StudentAssessmentMart.dbo.vwStateAssessmentInformation sai

inner join StudentAssessmentMart.dbo.FctAssessmentStateSubject fct
    on sai.StudentDWID = fct.StudentDWID

inner join StudentAssessmentMart.dbo.DimStateAssessmentProficiencySubject aps
    on fct.StateAssessmentProficiencySubjectDMID = aps.StateAssessmentProficiencySubjectDMID

inner join StudentAssessmentMart.dbo.DimAssessmentSubject sub
    on sub.AssessmentSubjectDWID = fct.AssessmentSubjectDWID

inner join StudentAssessmentMart.dbo.DimAssessmentResults dar
    on dar.AssessmentScoreCategoryDWID = fct.AssessmentScoreCategoryDWID

where sai.Proficiency != 'Unknown Proficiency'
and dar.Proficiency != 'Unknown Proficiency'
and sai.StudentBKID = 174957
and sai.Subject not in ('Science','Social Studies','SocStud','Listening','writing','sci','citizenship')
and sai.gradeabbreviation not in ('k','1','2','unknown')
order by StudentBKID

select distinct min(AcademicYearNum) 'min', max(AcademicYearNum)'max', StudentBKID
into #new
from #main
group by StudentBKID

select distinct *, 'min year' as minmaxyear from #main main
inner join #new newtable
    on newtable.StudentBKID = main.StudentBKID
    and newtable.min=main.AcademicYearNum

where StateAssessmentProficiencySubjectName <> 'Not Applicable'

union

select distinct *, 'max year' as minmaxyear from #main main
inner join #new newtable
    on newtable.StudentBKID = main.StudentBKID
    and newtable.max=main.AcademicYearNum
and GradeAbbreviation = '8'

where StateAssessmentProficiencySubjectName <> 'Not Applicable'
order by main.StudentBKID
drop table #main, #new

1 个答案:

答案 0 :(得分:0)

一次注释掉一个连接,直到您不再获得重复项。然后集中精力重新编写连接,这样就不会造成重复。