select a.Score as Score,(selectcount(distinct b.Score)from Scores b where b.Score>=a.Score)as Rank
-- 创建临时表,(a b两表相同)查找b表中大于等于a表中的数据条数(用distinct去重),即为等级from Scores a
orderby Score DESC;
查找重复的邮箱
注:
顺序:where>groupby>having>orderby--方法一 group by + 临时表select Email
from(select Email,count(Email)as num from Person groupby Email)as a
--嵌套select要有别名where num>1--方法二:group by + havingselect Email
from Person
groupby Email
havingcount(Email)>1;
各部门工资最高的员工
-- 先用group by + max()查询出各部门最高的工资和部门idselect d.Name as'Department',e.Name as'Employee',Salary
from Employee e join Department d on e.DepartmentId=d.Id
where(DepartmentId,Salary)in(select DepartmentId,max(Salary)from Employee groupby DepartmentId)
删除重复的电子邮箱
-- 方法一:not inDELETEFROM Person
WHERE Id NOTIN(select Id from-- 要使用临时表,MySQL不允许select和delete操作同一个表(SELECTMIN(Id)AS Id FROM Person GROUPBY Email)as a
)-- 方法二:DELETE p1 FROM Person p1,Person p2
WHERE p1.Email = p2.Email AND p1.Id > p2.Id