SQL sorting does not follow group by statement, always uses primary key

前端 未结 4 1084
清酒与你
清酒与你 2021-01-15 06:40

I have a SQL database with a table called staff, having following columns:

workerID (Prim.key), name, department, salary

I am

4条回答
  •  半阙折子戏
    2021-01-15 06:51

    My favorite solution to this problem uses LEFT JOIN:

    SELECT m.workerID, m.name, m.department, m.salary
    FROM staff m             # 'm' from 'maximum'
        LEFT JOIN staff o    # 'o' from 'other'
            ON m.department = o.department    # match rows by department
            AND m.salary < o.salary           # match each row in `m` with the rows from `o` having bigger salary
    WHERE o.salary IS NULL       # no bigger salary exists in `o`, i.e. `m`.`salary` is the maximum of its dept.
    ;
    

    This query selects all the workers that have the biggest salary from their department; i.e. if two or more workers have the same salary and it is the bigger in their department then all these workers are selected.

提交回复
热议问题