Usage example of Mysql case then when

Title description

Get information about employees with bonuses.

CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,PRIMARY KEY (`emp_no`));
CREATE TABLE `employees` (
`emp_no` int(11) NOT NULL,
`birth_date` date NOT NULL,
`first_name` varchar(14) NOT NULL,
`last_name` varchar(16) NOT NULL,
`gender` char(1) NOT NULL,
`hire_date` date NOT NULL,PRIMARY KEY (`emp_no`));
CREATE TABLE `dept_emp` (
`emp_no` int(11) NOT NULL,
`dept_no` char(4) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,PRIMARY KEY (`emp_no`,`dept_no`));
create table emp_bonus(
emp_no int not null,
received datetime not null,
btype smallint not null);
CREATE TABLE `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`from_date`));

Subject requirements:

According to the above four tables, give emp_no, first_name, last_name, bonus type btype, corresponding current salary situation salary and bonus amount bonus. The bonus type btype is 1 and the bonus is 10% of the salary, and the btype is 2 the bonus is 20% of the salary, and the other types are 30% of the salary. The current salary represents to_date='9999-01-01' and the
output format is as follows:
Insert picture description here

answer

According to the requirements of the above questions, the analysis shows that this question mainly examines the knowledge points of case then when, and the other connection content is relatively simple. The code is as follows:

select e.emp_no,e.first_name,e.last_name,b.btype,s.salary,
(case b.btype 
when 1 then s.salary*0.1
when 2 then s.salary*0.2
when 3 then s.salary*0.3
end ) bonus
from employees e join emp_bonus b on e.emp_no=b.emp_no
join salaries s on e.emp_no=s.emp_no 
where s.to_date='9999-01-01'
group by e.emp_no;

The above is just a simple idea, for reference only.

Guess you like

Origin blog.csdn.net/giantleech/article/details/114403671