First filter the rows of each employee_id
for the status_id
s that you want.
Then rank the rows with ROW_NUMBER()
window function by applying the priorities that you want.
Finally pick the first row from each ranking:
WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY employee_id
ORDER BY status_id = 7 DESC,
status_id = 4 DESC,
status_id = 3 DESC, -- this is the last option and it is actually not needed
id
) AS rn
FROM employee_leaves
WHERE status_id IN (7, 4, 3)
)
SELECT id, employee_id, status_id
FROM cte
WHERE rn = 1;
使用函数FIELD()
可以简化ROW_NUMBER()
内的ORDER BY
子句:
ORDER BY FIELD(status_id, 7, 4, 3),
id
或功能FIND_IN_SET()
:
ORDER BY FIND_IN_SET(status_id, '7,4,3'),
id
See the demo.