DB2 CASE语句

Cra*_*iem 5 sql db2 case

我需要以某种方式使用CASE语法(超出我)来根据条件影响数据库结果.我在0中有一堆版税.#form(版税)我有一个标题ID#(title_id),我需要显示版税的新增加,以便我可以使用这些数据.

IF: they have a current royalty of 0.0 - 0.1 = 10% raise
IF: they have 0.11 - 0.15 = 20% raise
IF: royalty >= 0.16 =  20% raise
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激.

    create table royalites (
title_id    char(6),
lorange     integer,
hirange     integer,
royalty     decimal(5,2));
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 9

其实,你并不需要使用case语句:

update royalties set royalty = royalty * 1.2
    where royalty >= 0.16;
update royalties set royalty = royalty * 1.2
    where royalty >= 0.11 and royalty < 0.16;
update royalties set royalty = royalty * 1.1
    where royalty < 0.11;
Run Code Online (Sandbox Code Playgroud)

(在交易控制下,如果你需要原子性).如果它们具有与您的问题状态相同的乘数,则可以组合前两个.

它的工作原理是确保首先执行更高的值并限制在where子句中受影响的行.

如果您觉得必须使用case声明:

update royalties set royalty =
    case when royalty >= 0.16 then royalty * 1.2
    case when royalty >= 0.11 and royalty < 0.16 then royalty * 1.2
    case when royalty <  0.11 then royalty * 1.1
    end;
Run Code Online (Sandbox Code Playgroud)

要改变你从表中取出的内容(而不是更改表本身)并将其与当前进行比较:

select title_id, lorange, hirange, royalty,
    case when royalty >= 0.16 then royalty * 1.2
    case when royalty >= 0.11 and royalty < 0.16 then royalty * 1.2
    case when royalty <  0.11 then royalty * 1.1
    end as new_royalty
    from royalties;
Run Code Online (Sandbox Code Playgroud)