GROUP BY (Transact‑SQL)

The GROUP BY clause groups rows that have the same values in specified columns into aggregate data such as COUNT, SUM, AVG, MAX, or MIN. It is often used in conjunction with aggregate functions to produce summary results.

Syntax

SELECT 
    select_list 
FROM 
    table_expression 
[ WHERE 
    search_condition ] 
[ GROUP BY 
    { grouping_column_expression 
    | rollup_expression 
    | cube_expression } 
    [ ,...n ] 
    [ WITH ROLLUP ] 
    [ HAVING 
        search_condition ] ] 
[ ORDER BY 
    order_by_expression [ ASC | DESC ] [ ,...n ] ]

Remarks

Examples

Basic Grouping

SELECT 
    DepartmentID, 
    COUNT(*) AS EmployeeCount, 
    AVG(Salary) AS AvgSalary 
FROM 
    Employees 
GROUP BY 
    DepartmentID
ORDER BY 
    EmployeeCount DESC;
Note: The ORDER BY clause sorts the final grouped result set, not the rows before grouping.

Using WITH ROLLUP

SELECT 
    Country, 
    YEAR(OrderDate) AS OrderYear, 
    SUM(TotalAmount) AS YearlySales 
FROM 
    Orders 
WHERE 
    OrderDate >= '2023-01-01' 
GROUP BY 
    Country, YEAR(OrderDate) WITH ROLLUP
ORDER BY 
    Country, OrderYear;

See also