在SQL中,COUNT()和GROUP BY通常一起使用,用于统计每个组中的行数。这对于分组数据并计算每个组中的记录数量非常有用。以下是COUNT()和GROUP BY的一些妙用:
SELECT department, COUNT(*)
FROM employees
GROUP BY department;
SELECT department, COUNT(*)
FROM employees
WHERE salary > 5000
GROUP BY department;
SELECT department, position, COUNT(*)
FROM employees
GROUP BY department, position;
SELECT department, COUNT(*)
FROM employees
GROUP BY department
HAVING AVG(salary) > 5000;
总之,COUNT()和GROUP BY的结合可以用于分组数据、统计每个组中的行数以及过滤出符合条件的组,非常实用且灵活。