Master SQL GROUP BY: Organize and aggregate data
SQL GROUP BY
clause: Data grouping and summary
GROUP BY
clause of SQL is used to group data by the values of one or more columns. It is usually used in combination with aggregate functions (such as SUM
, COUNT
, AVG
, MAX
, MIN
) to calculate each group.
GROUP BY
Syntax
<code class="sql">SELECT column1, aggregate_function(column2) FROM table_name GROUP BY column1;</code>
-
column1
: Group by column. -
aggregate_function(column2)
: The aggregate function that acts on each group. -
table_name
: Data source table.
How GROUP BY
works
- Grouping: Rows with the same
column1
value are divided into the same group. - Aggregation: Apply an aggregate function to each group to calculate a single result.
Example table: Sales data
Product | Category | Sales_amount | Region |
---|---|---|---|
Laptop | Electronics | 1000 | North (north) |
Mobile phone (phone) | Electronics | 500 | South (south) |
TV (TV) | Electronics | 700 | North (north) |
Office desk (desk) | Furniture | 200 | East (east) |
Chair | Furniture | 150 | East (east) |
GROUP BY
usage example
1. Total sales are calculated by category
<code class="sql">SELECT category, SUM(sales_amount) AS total_sales FROM sales GROUP BY category;</code>
result:
Category | Total sales (total_sales) |
---|---|
Electronics | 2200 |
Furniture | 350 |
2. Statistics the number of products in each category
<code class="sql">SELECT category, COUNT(product) AS product_count FROM sales GROUP BY category;</code>
result:
Category | Product quantity (product_count) |
---|---|
Electronics | 3 |
Furniture | 2 |
3. Group by multiple columns
<code class="sql">SELECT category, region, SUM(sales_amount) AS regional_sales FROM sales GROUP BY category, region;</code>
result:
Category | Region | Regional sales (regional_sales) |
---|---|---|
Electronics | North (north) | 1700 |
Electronics | South (south) | 500 |
Furniture | East (east) | 350 |
GROUP BY
combined with HAVING
The HAVING
clause is used to filter grouping results after grouping. Unlike the WHERE
clause, WHERE
clause filters rows before grouping.
Example: Filter categories with sales of more than 500
<code class="sql">SELECT category, SUM(sales_amount) AS total_sales FROM sales GROUP BY category HAVING SUM(sales_amount) > 500;</code>
result:
Category | Total sales (total_sales) |
---|---|
Electronics | 2200 |
GROUP BY
Important Tips
- Execution order: Grouping -> Aggregation ->
HAVING
Filtering. -
SELECT
column: Must appear inGROUP BY
clause or be used as an argument to the aggregate function.
Valid query:
<code class="sql">SELECT category, MAX(sales_amount) FROM sales GROUP BY category;</code>
Invalid query:
<code class="sql">SELECT Product, SUM(Sales_Amount) FROM sales GROUP BY Category; -- 错误:Product 不在GROUP BY 中,也不是聚合函数的参数</code>
- Multi-column grouping: You can use multiple columns to create a more detailed division.
- NULL value processing:
NULL
values are treated as a separate group.
Practical application scenarios
- Sales Statement: Calculate the total sales of each product or region.
- Inventory Management: Calculate the quantity of items in each category.
- Data analysis: Calculate the mean or sum by category, date, or position.
Summarize
GROUP BY
clause is a powerful data aggregation tool in SQL that can effectively generate meaningful analysis results. Proficiency in the use of GROUP BY
is crucial for efficient database queries.
Author: Abhay Singh Kathayat
Full-stack developer, proficient in front-end technology, and build efficient, scalable, user-friendly applications using a variety of programming languages and frameworks.
Contact email: kaashshorts28@gmail.com
The above is the detailed content of Master SQL GROUP BY: Organize and aggregate data. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The top ten digital virtual currency apps are: 1. OKX, 2. Binance, 3. gate.io, 4. Coinbase, 5. Kraken, 6. Huobi, 7. KuCoin, 8. Bitfinex, 9. Bitstamp, 10. Poloniex. These exchanges are selected based on factors such as transaction volume, user experience and security, and all provide a variety of digital currency trading services and an efficient trading experience.

Exchanges that support cross-chain transactions: 1. Binance, 2. Uniswap, 3. SushiSwap, 4. Curve Finance, 5. Thorchain, 6. 1inch Exchange, 7. DLN Trade, these platforms support multi-chain asset transactions through various technologies.

The steps to draw a Bitcoin structure analysis chart include: 1. Determine the purpose and audience of the drawing, 2. Select the right tool, 3. Design the framework and fill in the core components, 4. Refer to the existing template. Complete steps ensure that the chart is accurate and easy to understand.

Suggestions for choosing a cryptocurrency exchange: 1. For liquidity requirements, priority is Binance, Gate.io or OKX, because of its order depth and strong volatility resistance. 2. Compliance and security, Coinbase, Kraken and Gemini have strict regulatory endorsement. 3. Innovative functions, KuCoin's soft staking and Bybit's derivative design are suitable for advanced users.

Aavenomics is a proposal to modify the AAVE protocol token and introduce token repos, which has implemented a quorum for AAVEDAO. Marc Zeller, founder of the AAVE Project Chain (ACI), announced this on X, noting that it marks a new era for the agreement. Marc Zeller, founder of the AAVE Chain Initiative (ACI), announced on X that the Aavenomics proposal includes modifying the AAVE protocol token and introducing token repos, has achieved a quorum for AAVEDAO. According to Zeller, this marks a new era for the agreement. AaveDao members voted overwhelmingly to support the proposal, which was 100 per week on Wednesday

The steps to register for Bitget in 2025 include: 1. Prepare a valid email or mobile phone number and a stable network; 2. Visit the Bitget official website; 3. Enter the registration page; 4. Select the registration method; 5. Fill in the registration information; 6. Agree to the user agreement; 7. Complete verification; 8. Obtain and fill in the verification code; 9. Complete registration. After registering, it is recommended to log in to the account, perform KYC identity verification, and set up security measures to ensure the security of the account.

Cryptocurrency data platforms suitable for beginners include CoinMarketCap and non-small trumpet. 1. CoinMarketCap provides global real-time price, market value, and trading volume rankings for novice and basic analysis needs. 2. The non-small quotation provides a Chinese-friendly interface, suitable for Chinese users to quickly screen low-risk potential projects.

The platforms that have outstanding performance in leveraged trading, security and user experience in 2025 are: 1. OKX, suitable for high-frequency traders, providing up to 100 times leverage; 2. Binance, suitable for multi-currency traders around the world, providing 125 times high leverage; 3. Gate.io, suitable for professional derivatives players, providing 100 times leverage; 4. Bitget, suitable for novices and social traders, providing up to 100 times leverage; 5. Kraken, suitable for steady investors, providing 5 times leverage; 6. Bybit, suitable for altcoin explorers, providing 20 times leverage; 7. KuCoin, suitable for low-cost traders, providing 10 times leverage; 8. Bitfinex, suitable for senior play
