#数据库SQL实战#【Day12】【完结】

--------------------------------------------------
学习用,欢迎讨论。
--------------------------------------------------
查看详细题目的方法:
复制以下题目内容;
Ctrl+F查找刚刚复制的题目即可。
--------------------------------------------------
题目56:获取所有员工的emp_no
select de.emp_no, de.dept_no, eb.btype, eb.recevied
from dept_emp as de left join emp_bonus as eb
on de.emp_no = eb.emp_no
题目问题很多...主要使用left join连接两张表,如果右表有内容则显示、没有内容则不显示。
--------------------------------------------------
题目57:使用含有关键字exists查找未分配具体部门的员工的所有信息
select * from employees as e where not exists
(select * from dept_emp as de where de.emp_no = e.emp_no)
使用exists会对employees表逐条查询,每次查询都会检查exists里面的条件语句,当条件语句能够返回行时,则为真;当条件语句不能返回行时,则为假。
key word: exists
--------------------------------------------------
题目58:获取employees中的行数据,且这些行也存在于emp_v中
select * from emp_v
根据题意和视图emp_v的内容,可以直接如上查询。
当然也有很多其他的方法,比如连接、where限制条件等等。
--------------------------------------------------
题目59:获取有奖金的员工相关信息
select e.emp_no, e.first_name, e.last_name, eb.btype, s.salary, (s.salary * eb.btype)/10.0 as bonus
from employees as e
inner join emp_bonus as eb on e.emp_no = eb.emp_no
inner join salaries as s on e.emp_no = s.emp_no
where s.to_date = '9999-01-01'
由于本题计算bonus可以直接使用一个函数表达,所以得到上述语句。当bonus不能用一个表达式表达时,可以使用case关键字,有如下语句:
select e.emp_no, e.first_name, e.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 e
inner join emp_bonus as eb on e.emp_no = eb.emp_no
inner join salaries as s on e.emp_no = s.emp_no
where s.to_date = '9999-01-01'
key word: case
--------------------------------------------------
题目60:统计salary的累计和running_total
select s1.emp_no, s1.salary,
(
    select sum(s2.salary) from salaries as 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'
order by s1.emp_no
首先根据输出的结果running_total是前面所有员工的salary之和,题干有问题。上面的语句没有使用group by,直接计算出running_total。也可以使用group by,如下:
select s1.emp_no, s1.salary, sum(s2.salary) as running_total
from salaries as s1 inner join salaries as s2
on s2.emp_no <= s1.emp_no
where s1.to_date = '9999-01-01'
and s2.to_date = '9999-01-01'
group by s1.emp_no
order by s1.emp_no
--------------------------------------------------
题目61:对于employees表中,给出奇数行的first_name
题干有问题,查询的应该是按照first_name排序后奇数行的内容。
select e1.first_name
from employees as e1
where
(
    select count(*)
    from employees as e2
    where e1.first_name <= e2.first_name
) % 2 = 1
通过排序和选择奇数行即可
--------------------------------------------------

全部评论
啊 一转眼就完结了
点赞 回复 分享
发布于 2018-10-07 16:56

相关推荐

点赞 11 评论
分享
牛客网
牛客企业服务