牛客网SQL刷题_20200609

NO.1

题目描述:

存在如下的视图:
create view emp_v as select * from employees where emp_no >10005;
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`));
获取employees中的行数据,且这些行也存在于emp_v中。注意不能使用intersect关键字。
(你能不用select * from employees where emp_no >10005 这条语句完成吗,挑战一下自己对视图的理解)

解答:

select * from employees where emp_no in (select emp_no from emp_v)

Memo:发这题,纯属感叹自己被侮辱了

NO.2

题目描述:

获取有奖金的员工相关信息。
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,
recevied 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'

解答:

select em.emp_no,em.first_name,em.last_name,eb.btype,s.salary,
(CASE eb.btype 
 WHEN 1 THEN s.salary * 0.1
 WHEN 2 THEN s.salary * 0.2
 ELSE s.salary * 0.3 END) AS bonus
from employees as em,emp_bonus as eb,salaries as s
where em.emp_no = eb.emp_no and eb.emp_no=s.emp_no
and s.to_date='9999-01-01'

Memo:一定要记牢啊,这可是京东面试题啊!!!

NO.3

题目描述:

按照salary的累计和running_total,其中running_total为前N个当前( to_date = '9999-01-01')员工的salary累计和,其他以此类推。 具体结果如下Demo展示。。
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`));

解答:

select s1.emp_no,s1.salary,(select sum(s2.salary) from salaries s2 where s2.emp_no<=s1.emp_no and s2.to_date = '9999-01-01' ) as running_total
from salaries as s1
where s1.to_date = '9999-01-01' 

Memo:第二次遇到了,自连接得方式

NO.4

题目描述:

对于employees表中,输出first_name排名(按first_name升序排序)为奇数的first_name
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`));

解答:

select e1.first_name
from (select e2.first_name,
      (select count(*) 
       from employees as e3 where e3.first_name <= e2.first_name) as rowrank 
      from employees as e2 ) as e1
where rowrank %2 <> 0 

Memo:还是先子查询,产生e2和e3进行比较。第一个使用子查询得到排序的rowrank,然后e3,e2的输出作为e1表
题目

你可能感兴趣的:(牛客网SQL刷题_20200609)