使用sql将多个字段值替换/更新为单个值

时间:2017-12-19 06:31:26

标签: sql-server

我的表就像:

id |  name |   subject
-------------------
1  | kil   |   btech
2  | Jim   |   BACHELOR OF TECHNOLOGY
3  | Joe   |   Btech
4  | Ruth  |    MCA
5  | priya |   Master in comp application
6  | dev   |   MASTER IN COMPUTER APPLICATION
7  | sen   |   Master in Computer Application

如何将相关字段值分组为单个名称,例如:

id |  name  |  subject
-------------------
1  | kil    |  BACHELOR OF TECHNOLOGY
2  | Jim    |  BACHELOR OF TECHNOLOGY
3  | Joe    |  BACHELOR OF TECHNOLOGY
4  | Ruth   |  Master in Computer Application
5  | priya  |  Master in Computer Application
6  | dev    |  Master in Computer Application
7  | sen    |  Master in Computer Application

2 个答案:

答案 0 :(得分:2)

创建一个具有相同课程同义词的表格。然后加入这两个表来获得结果

(这可能是最简单的方法,因为您可以在以后添加更多同义词而无需更改代码)

喜欢这个

CREATE TABLE dbo.t_Synonyms
(
    SeqNo INT IDENTITY(1,1),
    FalseText VARCHAR(255),
    DisplayText VARCHAR(255)
)

INSERT INTO t_Synonyms(FalseText,DisplayText)
VALUES('BTEC','BACHELOR OF TECHNOLOGY'),
('B.TECG','BACHELOR OF TECHNOLOGY'),
('MCA',' Master in Computer Application'),
    ('Master in comp application',' Master in Computer Application')
SELECT
    YT.ID,
    YT.NAME,
    [SUBJECT] = ISNULL(TS.DisplayText,YT.[SUBJECT])
    FROM YourTable YT
        LEFT JOIN t_Synonyms TS
            ON LTRIM(RTRIM(YT.[SUBJECT])) = LTRIM(RTRIM(TS.FalseText)) 

答案 1 :(得分:0)

update mytable set subject = case when subject = 'btech' or subject = 'Btech' then 'BACHELOR OF TECHNOLOGY' when subject = 'MCA' or subject = 'Master in comp application' then 'Master in Computer Application' end where subject = 'btech' or subject = 'Btech' or subject = 'MCA' or subject = 'Master in comp application'