原表:
如下为数据库的两张表,表1为员工表;表2为员工奖金表。请根据各小题的输出结果,写出各小题的sql语句,请均用一句SQL语句实现。
建表语句:
-- create database employee;
-- use employee;
create table Employee(Employee_id int,
First_name varchar(50),
Last_name varchar(50),
Salary int,
Joining_date datetime,
Department varchar(50));
create table Incentive(Employee_id int,
Incentive_date datetime,
Incentive_amount int);
alter table employee modify Joining_date varchar(50);
alter table Incentive modify Incentive_date varchar(50);
insert into employee values(1,'John','Abraham',1000000,'1-Jan-13','Banking');
insert into employee values(2,'Michael','Clarke',800000,'1-Jan-13','Insurance');
insert into employee values(3,'Roy','Thomas',700000,'1-Feb-13','Banking');
insert into employee values(4,'Tom','Jose',600000,'1-Feb-13','Insurance');
insert into employee values(5,'Jerry','Pinto',650000,'1-Feb-13','Insurance');
insert into employee values(6,'Philip','Mathew',750000,'1-Jan-13','Services');
insert into employee values(7,'Mark','King',650000,'1-Jan-13','Services');
insert into employee values(8,'Andrew','Lee',600000,'1-Feb-13','Insurance');
insert into incentive values(1,'1-Jan-13',5000);
insert into incentive values(2,'1-Jan-13',3000);
insert into incentive values(3,'1-Feb-13',4000);
insert into incentive values(1,'1-Jan-13',4500);
insert into incentive values(2,'1-Feb-13',3500);
-- 值得我学习!!!
1.输出第一个名字(First_name)包含’o’的所有雇员信息,并按薪资降序排列
输出结果如下:
SELECT *
FROM Employee
WHERE First_name LIKE '%o%'
ORDER BY Salary DESC
2.输出每月的总支出工资大于1500000的部门和对应的支出,按降序排序。
输出结果如下:
SELECT
Department AS dept_name,
SUM(salary) AS tatol_salary
FROM Employee
GROUP BY Department
HAVING tatol_salary>1500000
ORDER BY tatol_salary DESC
3.输出有奖金(Incentive)和没奖金的人数。
输出结果如下:
图1:
图2:
图3:
附正确代码:
-- 方法1:
-- 20200405
SELECT
sum(有无发奖金) AS 有奖金,
(COUNT(c.Employee_id) - sum(有无发奖金)) as 无奖金
FROM
(
SELECT
DISTINCT a.Employee_id ,b.Employee_id I_Emp,
CASE
WHEN b.Employee_id IS NULL THEN 0 ELSE 1 END AS `有无发奖金`
FROM employee a
LEFT JOIN incentive b ON a.Employee_id = b.Employee_id)c
-- 使用中文给字段命名时,注意不要使用中文引号;最好的做法是不写引号,或者写入英文文引号
-- 方法2 ---也别有一番韵味(尤其是特意给两个字段重命名)
select sum(case when m.iid is not null then 1 else 0 end) as '有奖金',
sum(case when m.iid is null then 1 else 0 end) as '无奖金'
from
(select distinct e.employee_id as eid,
-- e.First_name,
i.employee_id as iid
from employee e
left join incentive i
on e.employee_id = i.employee_id) m;
来自aishujuxueyuan月考题
学而实习之,不亦说乎!
还是要多锻炼一下自己独手写代码的能力;锻炼自己的思维逻辑性和逻辑连贯性,不能出错;