题目描述
获取有奖金的员工相关信息。
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`));
给出emp_no、first_name、last_name、奖金类型btype、对应的当前薪水情况salary以及奖金金额bonus。 bonus类型btype为1其奖金为薪水salary的10%,btype为2其奖金为薪水的20%,其他类型均为薪水的30%。 当前薪水表示to_date='9999-01-01'
思路:本题除了bonus字段,其他字段都可以直接获得,而bonus字段确实是本题想考察的内容,也即我们如何能在查询字段的时候进行计算,这里采用了MySQL中的case语句:
CASE语法一:
CASE expression
WHEN value1 THEN returnvalue1
WHEN value2 THEN returnvalue2
WHEN value3 THEN returnvalue3
……
ELSE defaultreturnvalue
END
CASE语法二:
CASE
WHEN condition1 THEN returnvalue1
WHEN condition 2 THEN returnvalue2
WHEN condition 3 THEN returnvalue3
……
ELSE defaultreturnvalue
END
本题答案:
select
a.emp_no as emp_no,
a.first_name as first_name,
a.last_name as last_name,
b.btype as btype,
b.salary as salary,
b.bonus as bonus
from
employees as a
inner join
(
select
s.emp_no,btype,salary,(
case btype
when 1 then salary*0.1
when 2 then salary*0.2
else salary*0.3
end) bonus
from salaries s,
emp_bonus eb
where
s.emp_no=eb.emp_no
and
s.to_date='9999-01-01'
) as b
on
a.emp_no=b.emp_no;