Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SQL Server POWER() Function
Next article icon

SQL Server Group Functions

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The group function in SQL Server provides a powerful tool for performing calculations on groups of rows, allowing you to group data based on specific criteria. This function is important when you want to analyze and summarize information from multiple records in a data structure. The basic group functions are COUNT, SUM, AVG, MAX, and MIN.

Syntax:

The basic syntax for using the grouping function involves a GROUP BY clause with the custom aggregation function. Here’s the whole process:

SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;

  • column1: The group of columns in which you want to pass the data.
  • aggregate_function(column2): The group function (e.g., COUNT, SUM, AVG, MAX, MIN) applied to the new columns of each group.
  • table_name: The name of the table containing the data.

Primary Grouping Functions

  • COUNT(): Counts the number of rows in each group.

SELECT column1, COUNT(*) as row_count
FROM table_name
GROUP BY column1;

  • SUM(): Calculates the sum of values in a column for each group.

SELECT column1, SUM(column2) as total_sum
FROM table_name
GROUP BY column1;

  • AVG(): Computes the average of values in a column for each group.

SELECT column1, AVG(column2) as average_value
FROM table_name
GROUP BY column1;

  • MAX(): Retrieves the maximum value in a column for each group.

SELECT column1, MAX(column2) as max_value
FROM table_name
GROUP BY column1;

  • MIN(): Retrieves the minimum value in a column for each group.

SELECT column1, MIN(column2) as min_value
FROM table_name
GROUP BY column1;

Grouping Functions Concept

  • The GROUP BY clause is used to group rows by the specified column(s).
  • Aggregate functions (SUM, COUNT, AVG, etc.) perform calculations on each group.

Examples of Grouping Functions in SQL Server

Let's create a simple example with an "employees" table and demonstrate the use of grouping functions.

Query

-- Step 1: Create the employees table
CREATE TABLE employees (
   employee_id INT PRIMARY KEY,
   employee_name VARCHAR(50),
   department VARCHAR(50),
   salary INT
);
-- Step 2: Insert sample data into the employees table
INSERT INTO employees (employee_id, employee_name, department, salary)
VALUES
   (1, 'John Doe', 'HR', 50000),
   (2, 'Jane Smith', 'IT', 60000),
   (3, 'Bob Johnson', 'HR', 55000),
   (4, 'Alice Williams', 'IT', 65000),
   (5, 'Charlie Brown', 'Finance', 70000)

Example 1: Using COUNT with GROUP BY

-- Step 3: Use Grouping Functions with the inserted data
SELECT department, COUNT(*) as employee_count
FROM employees
GROUP BY department;

Output:

Output
Output

Explanation:

  • Groups the employees table by the department column.
  • Counts the number of employees in each department using COUNT(*).

Example 2: Using AVG with GROUP BY

-- Step 3: Use Grouping Functions with the inserted data
SELECT department, AVG(salary) as avg_salary
FROM employees
GROUP BY department;

Output:
Output

Explanation:

  • Groups the employees table by the department column.
  • Calculates the average salary (AVG(salary)) for each department.

Example Output:

  1. In the output screenshot, you can see the result of the SQL query with grouped data and calculated values.
  2. Remember, the specific query and output will depend on your database schema and the data you have.

Conclusion

To sum up, grouping functions in SQL Server are essential for data analysis and summarization because they let you calculate values for sets of rows based on predefined standards. The principal grouping functions—COUNT, SUM, AVG, MAX, and MIN, among others offer strong instruments for compiling and drawing conclusions from your data.


Next Article
SQL Server POWER() Function
author
akashjha2671
Improve
Article Tags :
  • Geeks Premier League
  • SQL Server
  • Databases
  • Geeks Premier League 2023

Similar Reads

  • GROUPING ID Function in SQL Server
    SQL Server is a Relational Database Management System that is used to create and manipulate the database. It provides advanced security measures like encryption, access control, and auditing to protect sensitive data from unauthorized access. It Supports a wide range of data types, including structu
    6 min read
  • SQL Server POWER() Function
    The POWER() function in SQL Server is a mathematical function that computes the result of raising a number (the base) to the power of another number (the exponent). It is a versatile function used for various calculations, such as squaring a number, computing roots or applying exponential growth in
    4 min read
  • RANK() Function in SQL Server
    The RANK() function is a powerful window function in SQL Server used to assign a rank to each row within a result set. It is particularly useful when we need to assign a rank to a group of rows based on some sorting criteria and want to differentiate between rows that have the same values. Unlike ot
    5 min read
  • SQL General Functions
    SQL general functions are built-in tools provided by SQL databases to perform a variety of operations on data. These functions are crucial for manipulating, analyzing, and transforming data efficiently. In this article, We will learn about the what are the SQL General Functions along with the exampl
    5 min read
  • SUM() Function in SQL Server
    The SUM() function in SQL Server is an essential aggregate function used to calculate the total sum of values in a numeric column. It aggregates data by summing up all values in the specified column for the rows that match the criteria of the query. In this article, We will learn about SUM() Functio
    3 min read
  • AVG() Function in SQL Server
    The AVG() function in SQL Server is an essential aggregate function used to compute the average value of a numeric column. It works by summing all non-NULL values in the specified column and then dividing the total by the number of these values. In this article, We will learn about AVG() Function in
    4 min read
  • YEAR() Function in SQL Server
    The YEAR() function in SQL Server is a powerful tool designed to extract the year component from a given date or datetime expression. It allows users to isolate the year as an integer value and facilitating various date-related operations and analyses. In this article, We will learn about the YEAR()
    2 min read
  • REVERSE() Function in SQL Server
    The REVERSE() function in SQL Server is a simple and powerful tool designed to reverse the order of characters in a string. By taking a string input, it returns a new string with its characters arranged in the opposite sequence. In this article, We will learn to REVERSE() Functions in SQL Server by
    3 min read
  • COUNT() Function in SQL Server
    The COUNT() function in SQL Server is a fundamental aggregate function used to determine the number of rows that match a specific condition. Counting rows provides valuable insights into data sets such as the total number of records, distinct values, or records meeting certain criteria. In this arti
    3 min read
  • SQL | Numeric Functions
    SQL Numeric Functions are essential tools for performing mathematical and arithmetic operations on numeric data. These functions allow you to manipulate numbers, perform calculations, and aggregate data for reporting and analysis purposes. Understanding how to use SQL numeric functions is important
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences