不使用distinct,使用group by不起作用

时间:2017-10-23 19:52:59

标签: sql

SELECT  
    COALESCE(TranscriptCourses.SSID, CourseMemberhsip.SSID) SSID,
    COALESCE(CourseMemberhsip.DATE_OF_BIRTH ,TranscriptCourses.DATE_OF_BIRTH) DATE_OF_BIRTH,    
    COALESCE(CourseMemberhsip.DISTRICT_NUMBER , CourseMemberhsip.DISTRICT_NUMBER ) DISTRICT_NUMBER,
    TranscriptCourses.SCHOOL_NUMBER ,
    COALESCE(CourseMemberhsip.STATE_COURSE_CODE, TranscriptCourses.CORE_CODE) STATE_COURSE_CODE ,
    ISNULL(CourseMemberhsip.SECTION_EXIT_DATE, '9999-01-01') SECTION_EXIT_DATE ,
    (CourseMemberhsip.AvgGradeEarned, TranscriptCourses.AvgGradeEarned) AS AvgGradeEarned ,
    TranscriptCourses.SCHOOL_YEAR
FROM
    #transcripts TranscriptCourses
FULL OUTER JOIN 
    #GradeMembership CourseMemberhsip ON TranscriptCourses.SSID = CourseMemberhsip.SSID
                                      AND TranscriptCourses.CORE_CODE = CourseMemberhsip.STATE_COURSE_CODE
                                      AND TranscriptCourses.SCHOOL_YEAR = CourseMemberhsip.SCHOOL_YEAR
GROUP BY 
    SSID,
    STATE_COURSE_CODE,
    TranscriptCourses.SCHOOL_YEAR

1 个答案:

答案 0 :(得分:0)

如果您使用“group by”,您的所有列也应该在group by子句中声明,或者应该应用sum,avg,count,min,max等聚合函数...

选择完成后也不会应用分组依据,我的意思是你必须准确包含你的列在select子句中(在你的查询中,你只在组by子句中包含结果别名作为SSID,它应该是GROUP BY COALESCE(TranscriptCourses.SSID,CourseMemberhsip.SSID)没有别名部分。

并且select子句中存在列,但既没有包含在group by子句中也没有对它们应用聚合函数(DATE_OF_BIRTH,SCHOOL_NUMBER)

您应该在期待查询运行之前解决这些问题。

我建议您阅读有关使用组操作编写选择查询的信息......