Table of Contents
SQL GROUP BY clause: Data grouping and summary
GROUP BY Syntax
How GROUP BY works
Example table: Sales data
GROUP BY usage example
1. Total sales are calculated by category
2. Statistics the number of products in each category
3. Group by multiple columns
Example: Filter categories with sales of more than 500
GROUP BY Important Tips
Practical application scenarios
Summarize
Home Database Mysql Tutorial Master SQL GROUP BY: Organize and aggregate data

Master SQL GROUP BY: Organize and aggregate data

Apr 08, 2025 pm 06:36 PM
computer ai Mail Inventory management aggregate function

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>
Copy after login
  • column1 : Group by column.
  • aggregate_function(column2) : The aggregate function that acts on each group.
  • table_name : Data source table.

How GROUP BY works

  1. Grouping: Rows with the same column1 value are divided into the same group.
  2. 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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

result:

Category Total sales (total_sales)
Electronics 2200
---

GROUP BY Important Tips

  1. Execution order: Grouping -> Aggregation -> HAVING Filtering.
  2. SELECT column: Must appear in GROUP 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>
Copy after login

Invalid query:

 <code class="sql">SELECT Product, SUM(Sales_Amount) FROM sales GROUP BY Category; -- 错误:Product 不在GROUP BY 中,也不是聚合函数的参数</code>
Copy after login
  1. Multi-column grouping: You can use multiple columns to create a more detailed division.
  2. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Top 10 Digital Virtual Currency Apps Rankings: Top 10 Digital Currency Exchanges in Currency Circle Trading Apr 22, 2025 pm 03:00 PM

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.

What does cross-chain transaction mean? What are the cross-chain transactions? What does cross-chain transaction mean? What are the cross-chain transactions? Apr 21, 2025 pm 11:39 PM

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.

What is the analysis chart of Bitcoin finished product structure? How to draw? What is the analysis chart of Bitcoin finished product structure? How to draw? Apr 21, 2025 pm 07:42 PM

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.

What are the hybrid blockchain trading platforms? What are the hybrid blockchain trading platforms? Apr 21, 2025 pm 11:36 PM

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 recommendation to modify the AAVE protocol token and introduce token repurchase, which has reached the quorum number of people. Aavenomics is a recommendation to modify the AAVE protocol token and introduce token repurchase, which has reached the quorum number of people. Apr 21, 2025 pm 06:24 PM

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

bitget new user registration guide 2025 bitget new user registration guide 2025 Apr 21, 2025 pm 10:09 PM

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.

The top ten free platform recommendations for real-time data on currency circle markets are released The top ten free platform recommendations for real-time data on currency circle markets are released Apr 22, 2025 am 08:12 AM

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.

Ranking of leveraged exchanges in the currency circle The latest recommendations of the top ten leveraged exchanges in the currency circle Ranking of leveraged exchanges in the currency circle The latest recommendations of the top ten leveraged exchanges in the currency circle Apr 21, 2025 pm 11:24 PM

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

See all articles