您的位置:首页 > 汽车 > 新车 > SQL刷题笔记day6-1

SQL刷题笔记day6-1

2024/9/20 8:54:47 来源:https://blog.csdn.net/qq_47966193/article/details/139306547  浏览:    关键词:SQL刷题笔记day6-1

1从不订购的客户

分析:从不订购,就是购买订单没有记录,not in

我的代码:

select c.name as 'Customers'
from Customers c
where c.id not in (select o.customerId from Orders o)

2  部门工资最高的员工

分析:每个部门(group by),薪资最高(排序取第一 or max函数),员工

我的错误代码:

select  d.name 'Department' ,e.name 'Employee' ,e.salary 'Salary' 
from Employee e join Department d on e.departmentId = d.id
group by d.id
order by e.salary

正确代码:按照(部门id和最大薪资)进行查询,这样才能保证找出同部门可能存在的多个最高薪资的员工。

select  d.name 'Department' ,e.name 'Employee' ,e.salary 'Salary' 
from Employee e join Department d on e.departmentId = d.id
where (e.departmentId,e.salary) in #找每个部门最高薪资的(可能不止一个)
(select departmentId,max(salary) from Employee 
group by departmentId)

 3 删除重复的电子邮箱

分析:重复的好找,如何删除?select——delete

我的代码:delete不会用 第一次,好像是delete中不能用分组函数group by?

delete id,email
from Person
group by id
having count(email)>1

 为什么这样也不行呢:

delete from Person
where id in 
(select id
from Person
group by id
having count(email)>1)

官方答案:from后调用自身表两次,email相等,但是重复的前面id不等,不等则删掉

delete p1
FROM Person p1,Person p2
WHEREp1.Email = p2.Email AND p1.Id > p2.Id

 

好了好了不卷了

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com