根据条件逻辑更新表列值

时间:2015-01-30 15:35:47

标签: sql sql-server postgresql tsql sql-server-2008-r2

我有这样的表:

name | salary 
Tom  | 10000
Mary | 20000
Jack | 30000
Lisa | 40000
Jake | 60000

我需要一个更新查询来根据它包含的值更新salary列。

工资需要增加:

  • 5000表示10000到15000之间的值
  • 7000,值介于15000到20000之间
  • 8000表示值在20000到30000之间
  • 10000表示40000到60000之间的值

4 个答案:

答案 0 :(得分:2)

尝试使用CASE命令

中的UPDATE语句
UPDATE
    [yourtablename]
SET
    salary = 
         CASE 
            WHEN salary BETWEEN 10000 AND 15000 THEN salary + 5000 
            WHEN salary BETWEEN 15000 AND 20000 THEN salary + 7000 
            WHEN salary BETWEEN 20000 AND 30000 THEN salary + 8000 
            WHEN salary BETWEEN 40000 AND 60000 THEN salary + 10000 
            ELSE salary
         END 

答案 1 :(得分:1)

这样的事情:

UPDATE YourTable
SET salary = CASE 
                    WHEN salary > 10000 AND salary <= 15000 THEN salary + 5000
                    WHEN salary > 15000 AND salary <=20000 THEN salary + 7000
                    .
                    .
                    .
                END

答案 2 :(得分:1)

只需使用带有UPDATE语句的CASE语句,其中包含所需的逻辑:

UPDATE SalaryTable
SET Salary = 
    (CASE WHEN Salary BETWEEN 10000 AND 14999 THEN Salary + 5000
          WHEN Salary BETWEEN 15000 AND 19999 THEN Salary + 7000
          WHEN Salary BETWEEN 20000 AND 29999 THEN Salary + 8000
          WHEN Salary BETWEEN 40000 AND 59000 THEN Salary + 10000
          ELSE Salary
     END)

我使用BETWEEN来评估大于或等于小于或等于,因此像{{1}这样的值}。

此外,您在1499930000之间存在差距,但这并没有被提取,但我认为这是因为它是虚拟数据。

<强>参考:

SQL BETWEEN

SQL CASE

答案 3 :(得分:0)

这应该有效:

UPDATE T
SET T.Salary += CASE
        WHEN T.salary BETWEEN 10000 AND 15000 THEN 5000
        WHEN T.salary BETWEEN 15000 AND 20000 THEN 7000
        WHEN T.salary BETWEEN 20000 AND 30000 THEN 80000
        WHEN T.salary BETWEEN 40000 AND 60000 THEN 10000
        ELSE 0
    END
FROM YourTable AS T