數據庫分組排序的方法有兩種:按字段分組排序和按計算表達式分組排序。
SELECT department, MAX(salary) AS max_salary
FROM employees
GROUP BY department
ORDER BY max_salary DESC;
SELECT CASE WHEN (YEAR(hire_date) % 2) = 0 THEN 'Even' ELSE 'Odd' END AS hire_year_group,
COUNT(*) AS employee_count
FROM employees
GROUP BY hire_year_group
ORDER BY employee_count DESC;
無論使用哪種方法,分組排序都可以通過GROUP BY子句對結果進行分組,再通過ORDER BY子句對每個分組進行排序,從而得到按指定字段或計算表達式分組排序的結果。