从查询中排除0值

时间:2013-10-03 21:58:05

标签: sql sql-server

我必须得到我工作地点的学生的最终成绩。

查询效果很好,除非有0值,它包含它,这不可能发生。如何从查询中排除0,如果我没有弄错,0排除必须来自查询中的AVG。

这是我的问题:

SELECT 
gbc.StudentID as [Student ID],
per.FirstName + ' ' + per.MiddleName + ' ' + per.LastName as [Student Name], 
gbc.ClassID as [Class ID],
cls.Name as [Class Name],
ROUND(SUM(gbc.weightedgrade),0) as [Final Grade]
FROM (SELECT 
    gg.ClassID, 
    gg.StudentID, 
    ga.AssessmentId, 
    ga.Title , 
    AVG(gg.ReceivedPoints * ga.Weight / 100.0) as weightedgrade
FROM GbkAssessments as ga INNER JOIN GbkGrades as gg ON ga.AssessmentID = gg.AssessmentID AND ga.ClassID = gg.ClassID 
JOIN Classes as cls on ga.classID = cls.classID JOIN GbkSummary as gbs on ga.classID = gbs.classID
WHERE gg.StudentID = 1201417 and cls.YearID = 251 and gbs.TermID = 1
GROUP BY gg.StudentID, gg.ClassID, ga.AssessmentId, ga.Title) as gbc JOIN Classes as cls on gbc.classID = cls.classID 
join Person as Per on Per.PersonID = gbc.StudentID join Person_Student as PS on Per.PersonID = PS.StudentID 
GROUP BY gbc.StudentID, gbc.ClassID, cls.Name, per.FirstName, per.LastName, per.MiddleName
ORDER BY gbc.ClassID ASC

我的查询包括现有的一些评估中的0,但还没有值,例如尚未应用的测验,未检查的课堂作业。

如何从帐户中删除这些值?有没有AVGIFNOTNULL或类似的东西?

2 个答案:

答案 0 :(得分:0)

       AVG (CASE WHEN Value <> 0 THEN Value ELSE NULL END)

        SELECT 
        gbc.StudentID as [Student ID],
        per.FirstName + ' ' + per.MiddleName + ' ' + per.LastName as [Student Name], 
        gbc.ClassID as [Class ID],
        cls.Name as [Class Name],
        CASE WHEN gbc.weightedgrade IS NOT NULL THEN ROUND(SUM(gbc.weightedgrade),0) ELSE NULL END as [Final Grade]
        FROM (SELECT 
            gg.ClassID, 
            gg.StudentID, 
            ga.AssessmentId, 
            ga.Title , 
            CASE WHEN gg.ReceivedPoints IS NOT NULL AND ga.Weight IS NOT NULL  
              THEN
                 AVG(gg.ReceivedPoints * ga.Weight / 100.0) 
                ELSE NULL 
              END as weightedgrade
        FROM GbkAssessments as ga INNER JOIN GbkGrades as gg ON ga.AssessmentID = gg.AssessmentID AND ga.ClassID = gg.ClassID 
        JOIN Classes as cls on ga.classID = cls.classID JOIN GbkSummary as gbs on ga.classID = gbs.classID
        WHERE gg.StudentID = 1201417 and cls.YearID = 251 and gbs.TermID = 1
        GROUP BY gg.StudentID, gg.ClassID, ga.AssessmentId, ga.Title) as gbc JOIN Classes as cls on gbc.classID = cls.classID 
        join Person as Per on Per.PersonID = gbc.StudentID join Person_Student as PS on Per.PersonID = PS.StudentID 
        GROUP BY gbc.StudentID, gbc.ClassID, cls.Name, per.FirstName, per.LastName, per.MiddleName
        ORDER BY gbc.ClassID ASC

答案 1 :(得分:0)

我认为应该是这样的

将此添加到

的位置
and AVG(gg.ReceivedPoints * ga.Weight / 100.0) <>0