MySQL分組查詢是一種強(qiáng)大的功能,它允許你根據(jù)一個(gè)或多個(gè)列對結(jié)果集進(jìn)行分組,然后對每個(gè)組執(zhí)行聚合函數(shù),如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分組查詢,從而提高查詢性能和結(jié)果可讀性。