赞
踩
题目描述:
表: 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
注:
使用的是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
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
题目描述:
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
注意事项:
update和case when then else end的结合应用
题目描述:
表: 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)
注意事项:
删除,我用的delete和select一起用,除了只出现过一次的电子邮箱和出现过多次但id不是最小的那个电子邮箱之外,其余的都要删除。或者也可以:
delete p1.* from Person as p1,Person as p2
where p1.email=p2.email and p1.id>p2.id
但是上一个时间比较短
第二天,继续加油!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。