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分组查询,从而提高查询性能和结果可读性。