2015-05-17 84 views
1

我想查詢使用大小寫的總標記列,並獲得各個等級的標記並將其存儲爲單獨的列。我一直在嘗試一段時間,但它一直給我錯誤。使用mysql時的情況

SELECT gradecalc.StudentId,gradecalc.CourseCode, Total, 
    CASE TOTAL 
     WHEN >90 THEN 'AA' 
     WHEN <90 AND >85 THEN 'BA' 
     WHEN <85 AND >=80 THEN 'BB' 
     WHEN <80 AND >=75 THEN 'CB' 
     WHEN <75 AND >=70 THEN 'CC' 
     WHEN <70 AND >=65 THEN 'DC' 
     WHEN <65 AND >=60 THEN 'DD' 
     ELSE 'FF' 
    END AS Grade 

    FROM GRADECALC GROUP BY gradecalc.StudentId,gradecalc.CourseCode 
+0

有什麼錯誤? – kerem

+0

[文檔](https://dev.mysql.com/doc/refman/5.0/en/case.html)非常清晰。 –

回答

0

case <column> when <value>語法只能處理相等檢查。對於其他運營商,your'd必須使用一個稍微不同的語法:

SELECT gradecalc.StudentId,gradecalc.CourseCode, Total, 
CASE 
    WHEN total > 90 THEN 'AA' 
    WHEN total < 90 AND total >= 85 THEN 'BA' 
    WHEN total < 85 AND total >= 80 THEN 'BB' 
    WHEN total < 80 AND total >=75 THEN 'CB' 
    WHEN total < 75 AND total >=70 THEN 'CC' 
    WHEN total < 70 AND total >=65 THEN 'DC' 
    WHEN total < 65 AND total >=60 THEN 'DD' 
    ELSE 'FF' 
END AS Grade 
FROM GRADECALC GROUP BY gradecalc.StudentId,gradecalc.CourseCode 
0

你需要把在case when的充分體現。您的case <variable> when <constant>的語法僅適用於常量。

現在,您還可以簡化表達式,因爲case按順序處理。因此,這是相當於邏輯:

SELECT gc.StudentId, gc.CourseCode, gc.Total, 
     (CASE WHEN TOTAL > 90 THEN 'AA' 
      WHEN TOTAL > 85 THEN 'BA' 
      WHEN TOTAL >= 80 THEN 'BB' 
      WHEN TOTAL >= 75 THEN 'CB' 
      WHEN TOTAL >= 70 THEN 'CC' 
      WHEN TOTAL >= 65 THEN 'DC' 
      WHEN TOTAL >= 60 THEN 'DD' 
      ELSE 'FF' 
     END) AS Grade 
FROM GRADECALC gc 
GROUP BY gc.StudentId, gc.CourseCode ; 

我不認爲GROUP BY是必要的,除非你有一個給定的學生,當然多行。如果你這樣做,那麼你可能想AVG(Total)或類似case聲明中的。

有了這個公式,你可以很容易地看到「90」和「85」是可疑的。事實上,你原來的邏輯會給學生提供這些標記爲「FF」,我猜這不是意圖。

所以:

SELECT gc.StudentId, gc.CourseCode, gc.Total, 
     (CASE WHEN TOTAL >= 90 THEN 'AA' 
      WHEN TOTAL >= 85 THEN 'BA' 
      WHEN TOTAL >= 80 THEN 'BB' 
      WHEN TOTAL >= 75 THEN 'CB' 
      WHEN TOTAL >= 70 THEN 'CC' 
      WHEN TOTAL >= 65 THEN 'DC' 
      WHEN TOTAL >= 60 THEN 'DD' 
      ELSE 'FF' 
     END) AS Grade 
FROM GRADECALC gc; 
1

你可以試試這個,隊友:

SELECT 
    gc.StudentId, 
    gc.CourseCode, 
    gc.Total, 
    CASE 
     WHEN gc.Total > 90 THEN 'AA' 
     WHEN gc.Total BETWEEN 85 AND 90 THEN 'BA' 
     WHEN gc.Total BETWEEN 80 AND 85 THEN 'BB' 
     WHEN gc.Total BETWEEN 75 AND 80 THEN 'CB' 
     WHEN gc.Total BETWEEN 70 AND 75 THEN 'CC' 
     WHEN gc.Total BETWEEN 65 AND 70 THEN 'DC' 
     WHEN gc.Total BETWEEN 60 AND 65 THEN 'DD' 
     ELSE 'FF' 
    END AS Grade 
FROM 
    gradecalc gc 
GROUP BY 
    gc.StudentId, gc.CourseCode;