在寫SQL解決業務問題遇到的一種情況

原表:

如下爲數據庫的兩張表,表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月考題

學而實習之,不亦說乎!
還是要多鍛鍊一下自己獨手寫代碼的能力;鍛鍊自己的思維邏輯性和邏輯連貫性,不能出錯;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章