在SQL中,COUNT()和GROUP BY通常一起使用,用于統(tǒng)計每個組中的行數(shù)。這對于分組數(shù)據(jù)并計算每個組中的記錄數(shù)量非常有用。以下是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的結(jié)合可以用于分組數(shù)據(jù)、統(tǒng)計每個組中的行數(shù)以及過濾出符合條件的組,非常實(shí)用且靈活。