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分组查询,从而提高查询性能和结果可读性。
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
推荐阅读:MySQL子查询有哪些使用技巧