SQL-将字母转换为数字

时间:2018-11-24 12:53:31

标签: sql

我的任务是将字母等级(A,B +,D-,...)转换为数字形式。 A为1,B = 2,.. +表示相减0.3,-表示相加0.3(例如B- = 2.3和D + = 3.7) 是否有任何查询来解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用映射表并加入LEFT(letter, 1)。然后使用CASE添加或删除功能RIGHT(letter, 1)

中的0.3
WITH
grades(letter) AS (
    VALUES ('A'), ('A+'), ('B'), ('B-'), ('D+'), ('F-')
),
mapping(letter, num) AS (
    VALUES ('A', 1), ('B', 2), ('C', 3), ('D', 4), ('E', 5), ('F', 6)
)
SELECT
    grades.letter AS grade,
    CASE 
        WHEN RIGHT(grades.letter, 1) = '+' THEN mapping.num - 0.3
        WHEN RIGHT(grades.letter, 1) = '-' THEN mapping.num + 0.3
        ELSE mapping.num
    END AS num
FROM
    grades
JOIN
    mapping ON mapping.letter = LEFT(grades.letter, 1);

结果:

 grade | num
-------+-----
 A     |   1
 A+    | 0.7
 B     |   2
 B-    | 2.3
 D+    | 3.7
 F-    | 6.3
(6 rows)