GROUP BY
The GROUP BY
clause lets you group rows that share the same values in specified columns. It's commonly used with aggregate functions like COUNT()
, SUM()
, and AVG()
to summarize data by category.
Why Use GROUP BY?
It allows you to answer questions like:
- How many orders were placed in each region?
- What's the total sales per client?
- What's the average order value by region?
Basic Syntax
The GROUP BY
clause is used after the FROM
clause in a SELECT
statement.
SELECT column_name, AGG_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
You group by a column, then apply an aggregate function to summarize each group.
좋습니다. 지금까지 만든 groupby_numeric.sqlite
와 실습 SQL 코드를 바탕으로, 이어지는 교육 자료를 초보자도 따라 할 수 있도록 작성해 드리겠습니다.
아래 내용은 지금 작성하신 문서에 그대로 이어 붙이면 됩니다.
Step-by-Step Practice
We will use the clients
table, which contains:
client_id | name | region | sales | orders_count | |
---|---|---|---|---|---|
1 | Client 1 | client1@example.com | Texas | 8041 | 19 |
2 | Client 2 | client2@example.com | New York | 8619 | 3 |
... | ... | ... | ... | ... | ... |
Count Clients per Region
By using GROUP BY
with COUNT(*)
, we can count how many clients belong to each region.
-- Count how many clients there are in each region
SELECT region, COUNT(*) AS client_count
FROM clients
GROUP BY region;
Total Sales per Region
By using GROUP BY
with SUM(sales)
, we can calculate the total sales for each region.
-- Show total sales in each region
SELECT region, SUM(sales) AS total_sales
FROM clients
GROUP BY region;
Average Sales per Region
By using GROUP BY
with AVG(sales)
, we can calculate the average sales for each region.
-- Show average sales in each region
SELECT region, AVG(sales) AS avg_sales
FROM clients
GROUP BY region;
Key Takeaways
GROUP BY
groups rows with the same value in the specified column(s).- Aggregate functions like
COUNT()
,SUM()
, andAVG()
summarize each group. - The order of clauses matters:
SELECT
FROM
GROUP BY
ORDER BY
(optional for sorting groups)
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.