Sql server 多表查询

--查询出武汉地区的所有员工信息,要求显示部门名城及员工详细资料
select * from People left join Department on People.DepartmentId=Department.DepartmentId
select PeopleId 员工编号,DepartmentName 部门名称,PeopleName 员工姓名 from  People left join Department on People.DepartmentId=Department.DepartmentId

--查询出西安地区所有员工信息,显示部门名称,职级名称,员工的详细资料
select *
from People
left join Department on People.DepartmentId=Department.DepartmentId
left join Rank on People.RankId=Rank.RankId
where PeopleAddress ='西安'

--注意:查询DepartmentId 需要前面加上表名 因为有两个表中都有DepartmentId
select PeopleId 员工编号,People.DepartmentId 部门编号 ,DepartmentName 部门名称,PeopleName 员工姓名
from People
left join Department on People.DepartmentId=Department.DepartmentId
left join Rank on People.RankId=Rank.RankId
where PeopleAddress='西安'
--根据部门分组统计员工人数,员工工资总和,平均工资,最高工资和最低工资
select Department.DepartmentId 部门编号, count(*) 员工人数,sum(PeopleSalary)员工工资总和,avg(PeopleSalary)平均工资,max(PeopleSalary)最低工资,min(PeopleSalary)最低工资
from People
inner join Department on People.DepartmentId=Department.DepartmentId
group by Department.DepartmentId,DepartmentName

--根据部门分组统计员工人数,员工工资总和,平均工资,最高工资,和最低工资
--平均工资在6000以下的不参与统计,并且根据平均工资降序排序
select Department.DepartmentId 部门编号, count(*) 员工人数,sum(PeopleSalary)员工工资总和,avg(PeopleSalary)平均工资,max(PeopleSalary)最低工资,min(PeopleSalary)最低工资
from People
inner join Department on People.DepartmentId=Department.DepartmentId
group by Department.DepartmentId,DepartmentName
having avg(PeopleSalary)>=6000
order by avg(PeopleSalary) desc
--根据部门名称,然后根据职位名称
--分组统计员工人数 ,员工工资总和,平均工资,最高工资,和最低工资
select DepartmentName 部门名称,[Rank].RanktName 职位名称,count(*)员工人数,sum(PeopleSalary)员工工资总和,avg(PeopleSalary)平均工资,max(PeopleSalary)最低工资,min(PeopleSalary)最低工资
from People 
inner join Department on People.DepartmentId=Department.DepartmentId
inner join [Rank] on People.rankId=Rank.RankId
group by Department.DepartmentId,DepartmentName,Rank.RankId,RanktName

--自连接(自己连自己)
create table Dept
(

DeptId int Primary key,
DeptName varchar(50),
ParentId int ,

)
--一级

insert into Dept(DeptId,DeptName,ParentId ) values(1,'软件部',0)
insert into Dept(DeptId,DeptName,ParentId ) values(2,'硬件部',0)

--二级
insert into Dept(DeptId,DeptName,ParentId ) values(3,'软件研发部',1)
insert into Dept(DeptId,DeptName,ParentId ) values(4,'软件测试部',1)
insert into Dept(DeptId,DeptName,ParentId ) values(5,'硬件研发部',2)
insert into Dept(DeptId,DeptName,ParentId ) values(6,'软件测试部',2)

select * from Dept

--部门编号 部门名称 上级部门
--3			软件研发部 软件部
--4			软件测试部  软件部


select A.DeptId 部门编号,A.DeptName 部门名称 ,B.DeptName 上级部门 from Dept A
inner join Dept B
on A.ParentId=B.DeptId

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_53944811

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值