SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL GROUP BY Tutorial

Example Table

We will use the following table named sales for our examples:


    CREATE TABLE sales (
        sale_id INT PRIMARY KEY,
        product_name VARCHAR(50),
        sale_date DATE,
        amount DECIMAL(10, 2)
    );

    INSERT INTO sales (sale_id, product_name, sale_date, amount) VALUES
    (1, 'Product A', '2023-01-01', 100.00),
    (2, 'Product B', '2023-01-02', 150.00),
    (3, 'Product A', '2023-01-03', 200.00),
    (4, 'Product C', '2023-01-04', 250.00),
    (5, 'Product B', '2023-01-05', 300.00);
    

Sales Table

sale_id product_name sale_date amount
1 Product A 2023-01-01 100.00
2 Product B 2023-01-02 150.00
3 Product A 2023-01-03 200.00
4 Product C 2023-01-04 250.00
5 Product B 2023-01-05 300.00

Using SQL GROUP BY

The SQL GROUP BY statement is used to arrange identical data into groups. This statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to perform operations on each group of data.

Example 1: Total Sales Amount by Product

To calculate the total sales amount for each product, use the following query:


    SELECT product_name, SUM(amount) AS total_amount
    FROM sales
    GROUP BY product_name;
    

Result:

product_name Product A
total_amount 300.00
Product B
450.00
Product C
250.00

Example 2: Average Sales Amount by Product

To calculate the average sales amount for each product, use the following query:


    SELECT product_name, AVG(amount) AS average_amount
    FROM sales
    GROUP BY product_name;
    

Result:

product_name Product A
average_amount 150.00
Product B
225.00
Product C
250.00