LeetCode (627) - exchange wages

topic:

Given a salary table, as shown below, there are m = f = male and female values. F and m are all exchange value (e.g., change the value of m f all, and vice versa). It requires only one update (the Update) statement, and no intermediate temporary table.

Note that you will only write an Update statement, please do not write any Select statement.

E.g:

id name sex salary
1 A m 2500
2 B f 1500
3 C m 5500
4 D f 500

After running the update statements you have written, you will get the following table:

id name sex salary
1 A f 2500
2 B m 1500
3 C f 5500
4 D m 500

Used functions:

  • case function
  • case when expr1 then v1[when expr2 then v2] [ else vn ] end

case identification function start, end indicates the end of the function. If the expression expr1 established, the return value v1. If the expression expr2 when established, the return value v2, and so, finally encountered else, the return value of vn

  • case expr when e1 then v1 [when e2 then v2] [else vn] end
    if the value of the expression expr when e1, return v1. The value e2, return v2. And so, finally encountered else, return vn.

answer

//1
update salary set sex=( case sex when 'm' then 'f' else 'm' end);
//2
update salary set sex=(case when sex='m' then 'f' when sex='f' then 'm' end);
//3
update salary set sex=char(ascii('m')+ascii('f')-ascii(sex));
//4
update salary set sex=char(ascii('m')^ascii('f')^ascii(sex));

Guess you like

Origin blog.csdn.net/Fly_Fly_Zhang/article/details/95305037