SQL变量

https://leetcode-cn.com/problems/department-top-three-salaries/description/

SELECT
    d.Name AS Department,
    e.Name AS Employee,
    e.Salary AS Salary
FROM
    Department AS d
JOIN(
      SELECT
        t.*,
        (CASE @k WHEN DepartmentId THEN @n := IF(@s=Salary,@n,@n+1) ELSE @n := 1 END) AS n,
        IF(@k = DepartmentId, @k, @k := DepartmentId) AS k,
        @s := Salary AS s
      FROM
        (SELECT @n := 0, @k := 0, @s := 0) AS _,
        (SELECT * FROM Employee ORDER BY DepartmentId ASC, Salary DESC) AS t
    ) AS e ON d.Id = e.DepartmentId
WHERE e.n < 4;

发表评论

电子邮件地址不会被公开。 必填项已用*标注