牛客在线编程练习:SQL16_中等

SQL练习:SQL16_中等


题目:
统计出当前(titles.to_date=‘9999-01-01’)各个title类型对应的员工当前(salaries.to_date=‘9999-01-01’)薪水对应的平均工资。结果给出title以及平均工资avg。

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`));

CREATE TABLE IF NOT EXISTS "titles" (
`emp_no` int(11) NOT NULL,
`title` varchar(50) NOT NULL,
`from_date` date NOT NULL,
`to_date` date DEFAULT NULL);

如插入:
INSERT INTO salaries VALUES(10001,88958,'1986-06-26','9999-01-01');
INSERT INTO salaries VALUES(10003,43311,'2001-12-01','9999-01-01');
INSERT INTO salaries VALUES(10004,70698,'1986-12-01','1995-12-01');
INSERT INTO salaries VALUES(10004,74057,'1995-12-01','9999-01-01');
INSERT INTO salaries VALUES(10006,43311,'2001-08-02','9999-01-01');
INSERT INTO salaries VALUES(10007,88070,'2002-02-07','9999-01-01');

INSERT INTO titles VALUES(10001,'Senior Engineer','1986-06-26','9999-01-01');
INSERT INTO titles VALUES(10003,'Senior Engineer','2001-12-01','9999-01-01');
INSERT INTO titles VALUES(10004,'Engineer','1986-12-01','1995-12-01');
INSERT INTO titles VALUES(10004,'Senior Engineer','1995-12-01','9999-01-01');
INSERT INTO titles VALUES(10006,'Senior Engineer','2001-08-02','9999-01-01');
INSERT INTO titles VALUES(10007,'Senior Staff','1996-02-11','9999-01-01');

在这里插入图片描述

题解

#方式1:隐式内连接
SELECT title,AVG(salary)
FROM salaries S,titles T
WHERE S.emp_no = T.emp_no AND T.to_date='9999-01-01' AND S.to_date='9999-01-01'
GROUP BY T.title

#方式2:显式内连接
SELECT title,AVG(salary)
FROM salaries S
INNER JOIN titles T ON S.emp_no = T.emp_no
WHERE T.to_date='9999-01-01' AND S.to_date='9999-01-01'
GROUP BY T.title

#方式3:左外连接
SELECT title,AVG(salary)
FROM salaries S
LEFT OUTER JOIN titles T ON S.emp_no = T.emp_no
WHERE T.to_date='9999-01-01' AND S.to_date='9999-01-01'
GROUP BY T.title

#方式4:右外连接
SELECT title,AVG(salary)
FROM salaries S
RIGHT OUTER JOIN titles T ON S.emp_no = T.emp_no
WHERE T.to_date='9999-01-01' AND S.to_date='9999-01-01'
GROUP BY T.title

## 1.【avg】函数修饰的字段默认命名为avg,不用重命名。

个人整理的笔记,仅供学习使用,有问题麻烦指正。
题目及解答思路均来源于:牛客网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值