您的位置:首页 > 数据库 > MySQL

MySQL (五) 下 sql 练习(查询分析)

2017-02-16 14:49 573 查看
环境搭建请查看 MySQL (五) DQL 数据查询语言(sql 语句)

1、请显示各个国家的编码,名称和人数,如果没有人,就显示亡国:

分析:

要查询的表: empl e department d

要查询的列: d.id, d.dname, ifnull(coun,’亡国’)

where条件:d.id = e.department_id

分组:group by d.id.

select d.*, ifnull(COUNT(*),'亡国') coun from
department d,empl e where d.id = e.department_id group by d.id


注意:由于消除了笛卡尔积,所以人数为空的国家就不会显示,这是就需要在加入 做外链接。

select a.id,a.dname,ifnull(coun,'亡国') from department a left outer join
(select d.*, COUNT(*) coun from
department d,empl e where d.id = e.department_id group by d.id) b on a.id = b.id```


2、列出各个国家人员的姓名,以及上级,如果自己就是主公就显示 主公。

分析:

要查询的表: empl e left outer join empl m,

要查询的列: e.name, m.name

where条件:e.mgr = m.id

select e.name,ifnull(m.name,'**主公**')
from empl e left outer join empl m
on e.mgr = m.id


3、列出所有早于主公登基日期的员工姓名,受雇日期,主公姓名,和登基日期。

分析:

要查询的表: empl e 和 主公表
(select id,name,hire from empl where job='主公') b


要查询的列: e.name,e.hire,b.name,b.hire

where条件:e.mgr = b.id and e.hire < b.hire;

select e.name,e.hire,b.name,b.hire '主公登基日期'
from empl e,(select id,name,hire from empl where job='主公') b
where e.mgr = b.id and e.hire < b.hire;


4、列出部门个人最高工资 高于 8000 的部门,和人数。

分析:

要查询的表: empl

要查询列: job count(*)

条件: max(sal)>8000 (分组后需要将该函数写在 having 后面)

分组: job

select job,count(*)
from empl e group by job
having max(sal)>=10000


5、列出各个国家 员工工资 高于所在国家平均工资的员工姓名 薪水 和所在国家的平均工资。

分析:

需要的表: empl e , 国家平均工资
(select department_id,svg(sal) sal from empl group by department_id) d


需要查询的: e.name,e.sal, d.sal

where 条件:
e.department_id = d.department_id
and e.sal>d.sal

select e.name,e.sal,e.department_id,d.sal from  empl e,
(select department_id,avg(sal) sal from empl group by department_id) d
where e.department_id = d.department_id and e.sal>d.sal


6、列出和诸葛亮一个职业的所有人员姓名 以及所在国家:

分析:

select e.name,e.job,d.dname
from empl e,department d
where e.department_id = d.id and job=(select job from empl where name='诸葛亮')


7,列出公司,每年的利润 和 增长百分比

数据库       lr :表示利润
create table ach(
year int,
lr   int
)
插入:
insert into ach values(2000,100),(2001,200),(2002,300),(2003,700),(2004,1500);
答案:
select y1.year,y2.lr,y1.lr,
ifnull(concat(round((y1.lr-y2.lr)/y1.lr*100,0),'%'),'0%') '增长比'
from ach y1 left outer join ach y2
on y1.year = y2.year+1 order by y1.year
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql 数据