力扣SQL刷题17

题目1:
给定一个 salary 表,如下图所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。
在这里插入图片描述
解题思路:
1、题目要求按条件更换列中的内容,“条件”我们想到的是sql里的case表达式。

2、case…when…的使用方法:

case when <判断表达式> then <表达式>
     when <判断表达式> then <表达式>
     when <判断表达式> then <表达式>
     ……
     else <表达式>
end

3、更新语句时需要用到update语句,update语句使用方法如下:

update 表名
set 列名 = 修改后的值;

代码实现:

update salary
set sex = (case sex
               when 'm' then 'f'
               else 'm'
           end);

结果:
在这里插入图片描述

题目2:
编写一个 SQL 查询,输出表中所有大国家的名称、人口和面积。(如果一个国家的面积超过 300 万平方公里,或者人口超过 2500 万,那么这个国家就是大国家。)
在这里插入图片描述
解题思路:用 or 连接两个条件
代码实现:

select name,population,area
from World 
where area >3000000 or population > 25000000 ;

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Txixi/article/details/116203918