1

私の:には、単純な一般的な加重平均計算がありますSELECT

SELECT ROUND(SUM((G.UnitsAcademic*GD.Grade))/SUM(G.UnitsAcademic),3) AS 'GWA'
FROM Gradesheet G 
INNER JOIN GradeSheetDetail AS GD 
    ON GD.GradesheetId=G.GradesheetId

ただし、一部の学生は非数値の成績(「試験なし」など)または空白の成績を持っています。上記のコードは引き続き値を計算して返します。

数値以外の値が計算に含まれる場合は、空白( "")を返したいのですが。SQLがこれを行う方法はありますか?

4

2 に答える 2

3

So first: Its a conceptually BAD IDEA to have numbers that shall be summed (or processed mathematically in any way) in VARCHAR fields. It would be better to store them to numeric fields (and have a different field for situations where they don't apply). (In fact I'm surprised MySQL lets you even SUM on a VARCHAR)

But I assume you can't change it so try this:

select CASE WHEN SUM(GD.Grade) > 0
            THEN ' ' 
            ELSE SELECT ROUND(SUM((G.UnitsAcademic*GD.Grade))/SUM(G.UnitsAcademic),3) 
            END AS 'GWA' 
            FROM Gradesheet G 
            INNER JOIN GradeSheetDetail AS GD 
                  ON GD.GradesheetId=G.GradesheetId
于 2012-04-09T05:17:22.570 に答える
2

Try this:

SELECT 
    CASE 
        WHEN 
            MAX(CASE WHEN GD.Grade = 'No Grade' OR GD.Grade = ' ' THEN 1 ELSE 0 END) = 1 THEN ' '
        ELSE 
            ROUND(SUM((G.UnitsAcademic*GD.Grade))/SUM(G.UnitsAcademic),3)  
    END AS 'GWA'  
FROM Gradesheet G  
INNER JOIN GradeSheetDetail AS GD  
      ON GD.GradesheetId = G.GradesheetId 

First, you need to check if there is at least one non-numeric field, if 'yes' then return blank, else calculate aggregate.

于 2012-04-09T05:23:24.583 に答える