当前位置:   article > 正文

力扣SQL入门第二天—— 排序&修改_(2)设计一个修改数据的问题(能够用到like和排序),并用sql实现

(2)设计一个修改数据的问题(能够用到like和排序),并用sql实现

1873. 计算特殊奖金

题目描述:
表: Employees
±------------±--------+
| 列名 | 类型 |
±------------±--------+
| employee_id | int |
| name | varchar |
| salary | int |
±------------±--------+
employee_id 是这个表的主键
此表的每一行给出了雇员id ,名字和薪水。
写出一个SQL 查询语句,计算每个雇员的奖金。如果一个雇员的id是奇数并且他的名字不是以’M’开头,那么他的奖金是他工资的100%,否则奖金为0。
返回的结果集请按照employee_id排序。
代码:

select employee_id,salary as bonus from Employees  where name not like 'M%' and employee_id%2!=0
union
select employee_id,salary=0 as bonus from Employees  where name like 'M%' or employee_id%2=0
order by employee_id
  • 1
  • 2
  • 3
  • 4

注:
使用的是union,用于合并两个或多个select语句的结果集,union内部的 select语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 select语句中的列的顺序必须相同。
当然,也可以用if else,但是union花费的时间少,或者还可以使用case

select employee_id,if(name not like 'M%' and employee_id%2!=0, salary, 0) as bonus
from Employees order by employee_id
  • 1
  • 2
select employee_id,
case when name not like 'M%' and employee_id%2!=0 then salary
else 0 end as bonus
from Employees order by employee_id
  • 1
  • 2
  • 3
  • 4

627. 变更性别

题目描述:
Salary 表:

±------------±---------+
| Column Name | Type |
±------------±---------+
| id | int |
| name | varchar |
| sex | ENUM |
| salary | int |
±------------±---------+
id 是这个表的主键。
sex 这一列的值是 ENUM 类型,只能从 (‘m’, ‘f’) 中取。
本表包含公司雇员的信息。
请你编写一个 SQL 查询来交换所有的 ‘f’ 和 ‘m’ (即,将所有 ‘f’ 变为 ‘m’ ,反之亦然),仅使用 单个 update 语句 ,且不产生中间临时表。
注意,你必须仅使用一条 update 语句,且 不能 使用 select 语句。
代码:

update Salary 
set sex=case when sex='m' then 'f'
else 'm'
end 
  • 1
  • 2
  • 3
  • 4

注意事项:
update和case when then else end的结合应用

196. 删除重复的电子邮箱

题目描述:
表: Person
±------------±--------+
| Column Name | Type |
±------------±--------+
| id | int |
| email | varchar |
±------------±--------+
id是该表的主键列。
该表的每一行包含一封电子邮件。电子邮件将不包含大写字母。
编写一个 SQL 删除语句来 删除 所有重复的电子邮件,只保留一个id最小的唯一电子邮件。
以 任意顺序 返回结果表。 (注意: 仅需要写删除语句,将自动对剩余结果进行查询)
代码:

delete from Person where id not in 
(select id from 
(select id from Person where id in (select min(id) from Person group by Email having count(Email)>1)
union 
select id from Person where Email in (select Email from Person group by Email having count(Email)=1))
a)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

注意事项:
删除,我用的delete和select一起用,除了只出现过一次的电子邮箱和出现过多次但id不是最小的那个电子邮箱之外,其余的都要删除。或者也可以:

delete p1.* from Person as p1,Person as p2
where p1.email=p2.email and p1.id>p2.id
  • 1
  • 2

但是上一个时间比较短
在这里插入图片描述
第二天,继续加油!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/927472
推荐阅读
相关标签
  

闽ICP备14008679号