MySQL分組查詢是一種強大的功能,它允許你根據一個或多個列對結果集進行分組,然后對每個組執行聚合函數,如COUNT、SUM、AVG等
示例:
SELECT department, COUNT(*) as num_employees
FROM employees
GROUP BY department;
示例:
SELECT department, COUNT(*) as num_employees, SUM(salary) as total_salary
FROM employees
GROUP BY department;
示例:
SELECT department, COUNT(*) as num_employees
FROM employees
GROUP BY department
HAVING num_employees > 10;
示例:
SELECT department, COUNT(*) as num_employees
FROM employees
GROUP BY department
ORDER BY num_employees DESC;
示例:
SELECT department, COUNT(DISTINCT employee_id) as unique_employees
FROM employees
GROUP BY department;
示例:
SELECT department, GROUP_CONCAT(employee_name ORDER BY employee_name SEPARATOR ', ') as employee_names
FROM employees
GROUP BY department;
示例:
SELECT department, COUNT(*) as num_employees
FROM employees
GROUP BY department WITH ROLLUP;
這些技巧可以幫助你更有效地使用MySQL分組查詢,從而提高查詢性能和結果可讀性。