mysql 取每个部门薪资最高的前3人

员工表:
QQ图片20180716142827.png

部门表:
QQ图片20180716144304.png

要求:取每个部门工资最高的前3人,如图:

QQ图片20180716150112.png

创建Employee(员工表),Department(部门表)

SQL:

SELECT
	d. NAME Department,
	e1. NAME Employee,
	e1.Salary Salary
FROM
	Employee e1,
	Employee e2,
	Department d
WHERE
	e1.departmentid = e2.departmentid
AND e1.salary <= e2.salary
AND e1.departmentid = d.id
GROUP BY
	e1.id
HAVING
	count(DISTINCT e2.salary) < 3
ORDER BY
	e1.departmentid DESC
    
or

SELECT
    d. NAME dName,
    e. NAME eName,
    e.salary
FROM
    Employee e
RIGHT JOIN Department d ON e.departmentid = d.Id
WHERE
    (
        SELECT
            count(1)
        FROM
            Employee
        WHERE
            departmentid = e.departmentid
        AND salary > e.salary
    ) < 3
ORDER BY
    e.departmentid ASC,
    e.salary DESC
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值