【353天】我愛刷題系列112(2018.01.24)

叨叨兩句

  1. ~

SQL習題007

1

找出全部員工當前(to_date='9999-01-01')具體的薪水salary狀況,對於相同的薪水只顯示一次,並按照逆序顯示
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));
spa

select distinct s.salary
from salaries s
where s.to_date = '9999-01-01'
order by s.salary desc;

2

獲取全部部門當前manager的當前薪水狀況,給出dept_no, emp_no以及salary,當前表示to_date='9999-01-01'
CREATE TABLE dept_manager (
dept_no char(4) NOT NULL,
emp_no int(11) NOT NULL,
from_date date NOT NULL,
to_date date NOT NULL,
PRIMARY KEY (emp_no,dept_no));
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));code

此題與前面第三題相似,思路以下:
一、先用INNER JOIN鏈接兩張表,限制條件是兩張表的emp_no相同,即d.emp_no = s.emp_no,而且將salaries用別名s代替,dept_manager用別名d代替
二、根據題意,要獲取當前manager的當前salary狀況,再加上限制條件d.to_date = '9999-01-01' AND s.to_date = '9999-01-01'便可(由於同一emp_no在salaries表中對應多條漲薪記錄,而當s.to_date = '9999-01-01'時是該員工當前的薪水記錄)

SELECT d.dept_no, d.emp_no, s.salary 
FROM salaries AS s INNER JOIN dept_manager AS d 
ON d.emp_no = s.emp_no
AND d.to_date = '9999-01-01'
AND s.to_date = '9999-01-01'
select d.dept_no,d.emp_no,s.salary
from salaries s,dept_manager d
where d.emp_no = s.emp_no
and s.to_date = '9999-01-01'
and d.to_date = '9999-01-01';

3

獲取全部非manager的員工emp_no
CREATE TABLE dept_manager (
dept_no char(4) NOT NULL,
emp_no int(11) NOT NULL,
from_date date NOT NULL,
to_date date NOT NULL,
PRIMARY KEY (emp_no,dept_no));
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));blog

方法一:使用NOT IN選出在employees但不在dept_manager中的emp_no記錄
SELECT emp_no FROM employees
WHERE emp_no NOT IN (SELECT emp_no FROM dept_manager)

方法二:先使用LEFT JOIN鏈接兩張表,再今後表中選出dept_no值爲NULL對應的emp_no記錄
SELECT emp_no FROM (SELECT * FROM employees LEFT JOIN dept_manager
ON employees.emp_no = dept_manager.emp_no)
WHERE dept_no IS NULL

方法三:方法二的簡版,使用單層SELECT語句便可
SELECT employees.emp_no FROM employees LEFT JOIN dept_manager
ON employees.emp_no = dept_manager.emp_no
WHERE dept_no IS NULL
相關文章
相關標籤/搜索