SQL GROUP BY Statement


Intro

The GROUP BY statement groups rows that have the same values into summary rows
The GROUP BY statement is often used with aggregate functions to group the result-set by one or more columns


Sample Data

This is the table we will use as an example:

SELECT * 
FROM ar_invoices
invoice# customer# salesperson# invoice_date invoice_amount amount_paid current_month_interest_charges total_interest_charges
1112019-06-17 10:43:53.727100.001.000.000.00
2222019-05-28 10:43:53.72750.000.005.0010.00
3322019-06-17 10:43:53.72770.000.0010.0020.00
4212019-07-07 10:43:53.72780.000.000.000.00

Syntax


SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s)
SELECT salesperson#, 
       SUM(invoice_amount) AS [Total Sales]
FROM ar_invoices
GROUP BY salesperson#
salesperson# Total Sales
1180.00
2120.00

Notice that if you add more columns to the SELECT statement, you must also add them to the GROUP BY statement or recieve an error such as this:

SELECT salesperson#,
       total_interest_charges,
       SUM(invoice_amount) AS [Total Sales]
FROM ar_invoices
GROUP BY total_interest_charges
Msg 8120 Level 16 State 1 Line 22
Column 'ar_invoices.salesperson#' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

This is the correct way:

SELECT salesperson#,
       total_interest_charges,
       SUM(invoice_amount) AS [Total Sales]
FROM ar_invoices
GROUP BY total_interest_charges,
         salesperson#
salesperson# total_interest_charges Total Sales
10.00180.00
210.0050.00
220.0070.00

Combine aggregates

Create summaries by combining aggregate functions

SELECT customer#,
       COUNT(salesperson#) AS [Number of Employees that Customer Used], 
       SUM(invoice_amount) AS [Total Sales]
FROM ar_invoices
GROUP BY customer#
customer# Number of Employees that Customer Used Total Sales
11100.00
22130.00
3170.00

HAVING

Use the HAVING clause to filter the results of an aggregate function

Syntax


SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s)
SELECT salesperson#, 
       SUM(invoice_amount) AS [Total Sales]
FROM ar_invoices
GROUP BY salesperson#
HAVING SUM(invoice_amount) > 130
salesperson# Total Sales
1180.00