在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的結合可以用于分組數據、統計每個組中的行數以及過濾出符合條件的組,非常實用且靈活。