Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

55 计算特殊奖金 #67

Open
astak16 opened this issue Sep 17, 2023 · 0 comments
Open

55 计算特殊奖金 #67

astak16 opened this issue Sep 17, 2023 · 0 comments
Labels

Comments

@astak16
Copy link
Owner

astak16 commented Sep 17, 2023

题目

题目链接:计算特殊奖金

编写解决方案,计算每个雇员的奖金。如果一个雇员的 id 是 奇数 并且他的名字不是以 'M' 开头,那么他的奖金是他工资的 100% ,否则奖金为 0 。

返回的结果按照 employee_id 排序。

Create table If Not Exists Employees (employee_id int, name varchar(30), salary int);
Truncate table Employees;
insert into Employees (employee_id, name, salary) values ('2', 'Meir', '3000');
insert into Employees (employee_id, name, salary) values ('3', 'Michael', '3800');
insert into Employees (employee_id, name, salary) values ('7', 'Addilyn', '7400');
insert into Employees (employee_id, name, salary) values ('8', 'Juan', '6100');
insert into Employees (employee_id, name, salary) values ('9', 'Kannon', '7700');

解析

本题考察了三个知识点:

  1. 判断 name 中首字母是 M 的方法有 LIKEREGEXP 两种:
    • 使用 LIKE,用左匹配:M%
    • 使用 REGEXP,正则匹配有很多种,正则的写法有很多种,就不一一列举了
      • ^M:以 M 开头
      • ^M.*:以 M 开头,后面跟任意字符
      • ^[^M]:以非 M 开头
    • 还有一个跟 REGEXP 类似的 RLIKE,也是匹配正则
  2. 匹配偶数方法有很多,可以看这题 620. 有趣的电影,用了 6 种方法判断奇数
  3. 条件判断如果满足输出 bonus 否者输出 0,有两种方法:
    • IFIF (condition, true, false)
    • CASECASE WHEN condition THEN true ELSE false END

掌握了上面的方法,你就可以写出 24SQL 语句了,下面是其中一种

SQL

SELECT
	employee_id,
	IF (employee_id % 2 != 0 AND name NOT LIKE 'M%', salary, 0) bonus
FROM
	Employees
ORDER BY employee_id;
@astak16 astak16 added the 简单 label Sep 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant