What is the difference between DISTINCT and GROUP BY?
What is the difference between DISTINCT and GROUP BY?
Both can remove duplicate rows, but DISTINCT only deduplicates the selected columns, while GROUP BY forms groups so you can compute aggregates per group.
-- same result: unique (department, job_title) pairs
SELECT DISTINCT department, job_title FROM employees;
SELECT department, job_title FROM employees GROUP BY department, job_title;
-- only GROUP BY can aggregate per group
SELECT department, COUNT(*) AS headcount, AVG(salary) AS avg_salary
FROM employees
GROUP BY department;
DISTINCT applies to the whole select list, not just the first column. SELECT DISTINCT a, b is unique (a, b) pairs.GROUP BY can be followed by HAVING and supports ROLLUP, CUBE and GROUPING SETS.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.