替换列值

时间:2015-03-26 11:32:55

标签: sql sql-server

我已经拿到了这张桌子,

Name       Rating
A            2
B            1 
C            5
D            3
E            1
F            4

我已经获得了评级系统

1-Excellent, 2-Very Good, 3-Good, 4-OK, 5-Poor

我想知道我是否可以替换表中的nueric值来获得以下结果表。

Name       Rating
A         Very Good
B         Excellent
C           Poor
D           Good
E         Excellent
F            OK

由于

6 个答案:

答案 0 :(得分:3)

我认为在现场更新您的数据不是一个好主意,最好存储评级的ID而不是数据的文本表示。但是你可以查询你的表并用文本替换int:

select
    Name,
    case Rating
        when 1 then 'Excellent'
        when 2 then 'Very Good,'
        when 3 then 'Good'
        when 4 then 'OK'
        when 5 then 'Poor'
    end as Rating
from <your table>

或者你可以创建一个查找表并加入它

create table Rating (id int, desc nvarchar(128))

insert into Rating (id, desc)
select 1, 'Excellent' union all
select 2, 'Very good' union all
select 3, 'Good' union all
select 4, 'OK' union all
select 5, 'Poor'

select
    t.Name,
    R.desc as Rating
from <your table> as t
    left outer join Rating as R on R.id = t.Rating

答案 1 :(得分:1)

使用CASE声明。当然,这仅在您的列未设置为数值时才有效。

UPDATE tblRatings
SET Rating = CASE WHEN 1 THEN 'Excellent'
                  WHEN 2 THEN 'Very Good'
                  WHEN 3 THEN 'Good'
                  WHEN 4 THEN 'OK'
                  ELSE 'Poor' 
             END

如果是,您需要使用SELECT声明;

SELECT CASE WHEN 1 THEN 'Excellent'
            WHEN 2 THEN 'Very Good'
            WHEN 3 THEN 'Good'
            WHEN 4 THEN 'OK'
            ELSE 'Poor' 
       END
  FROM tblRatings

答案 2 :(得分:1)

尝试使用Choose

如果sql-server 2012

像这样:

 select Rating,name,choose(Rating,'Excellent','Very Good','Good','OK','Excellent','Poor') from table

Fiddle Demo

答案 3 :(得分:-1)

UPDATE
    tbl
SET
    Rating = CASE Rating
               WHEN 'A' THEN 'Very Good'
               WHEN 'B' THEN 'Excellent'
               WHEN 'C' THEN 'Poor'
               WHEN 'D' THEN 'Good'
               WHEN 'E' THEN 'Excellent'
               WHEN 'F' THEN 'OK'
             END

答案 4 :(得分:-1)

您可以使用更新功能:

update yourtable set rating = 'Excellent' where rating = '1'

您可以对所有评分进行此更新

答案 5 :(得分:-1)

Update YOURTABLE

set Rating = case when '2' then ' Very good'
            when '3' then ' good' end