如何根据条件更改列名和值?

时间:2016-04-12 02:01:59

标签: sql sql-server

我想根据条件更改列名和值。 我的桌子是......

Roll    Name    Mark
3   Chaity  87
1   Anis    75
4   Unknown 30
2   Badol   0

我希望得到这样的

Roll    Name    Grade
3   Chaity  A+
1   Anis    A
4   Unknown F
2   Badol   F

标记和等级映射如下:

0 to 60 is F
61 to 79 is A
80 and above is A+

2 个答案:

答案 0 :(得分:3)

一个简单的CASE表达式就可以了:

SELECT
    Roll,
    Name,
    Grade = CASE 
                WHEN Mark <= 60 THEN 'F'
                WHEN Mark <= 79 THEN 'A'
                ELSE 'A+'
            END
FROM tbl

ONLINE DEMO

答案 1 :(得分:1)

您可以使用CASE WHEN ...或创建成绩表

SELECT Roll, Name, Grade = case when Mark >= 80 then 'A+'
                                when Mark between 61 and 79 then 'A'
                                else 'F'
                                end
FROM   yourtable

使用成绩表

SELECT t.Roll, t.Name, g.Grade
FROM   yourtable t
       outer apply
       (
            select x.Grade
            from   GradeTable x
            where  t.Mark between x.Mark_from and x.Mark_to
       ) g

但是,评分系统有点激烈吗?你得到A或失败:(