sql group by statement

SQL Functions

homeBack

Next

The GROUP BY Statement

  • The AVG() Function

    The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

    SQL GROUP BY Syntax

    SELECT column_name, aggregate_function(column_name)
    FROM table_name
    WHERE column_name operator value
    GROUP BY column_name

  • SQL GROUP BY Example

    We have the following “Orders” table:

    OrderID Date Price Customer
    1 2012/12/12 1000 Joy
    2 2012/12/16 1600 Sam
    3 2012/12/22 1700 Arjun
    4 2012/12/23 1300 Joy
    5 2012/12/30 2300 John
    6 2012/12/31 1400 Joy

    Now we want to find the total sum (total order) of each customer.

    We will have to use the GROUP BY statement to group the customers.

    We use the following SQL statement:

    SELECT Customer,SUM(Price) FROM Orders
    GROUP BY Customer

    The result-set will look like this:

    Customer SUM(Price)
    Joy 3700
    Sam 1600
    Arjun 1700
    John 2300

    Let’s see what happens if we omit the GROUP BY statement:

    SELECT Customer,SUM(Price) FROM Orders

    The result-set will look like this:

    Customer SUM(Price)
    Joy 9300
    Sam 9300
    Arjun 9300
    Joy 9300
    John 9300
    Joy 9300

    The result-set above is not what we wanted.

    Explanation of why the above SELECT statement cannot be used: The SELECT statement above has two columns specified (Customer and SUM(Price). The “SUM(Price)” returns a single value (that is the total sum of the “Price” column), while “Customer” returns 6 values (one value for each row in the “Orders” table). This will therefore not give us the correct result. However, you have seen that the GROUP BY statement solves this problem.

  • GROUP BY More Than One Column

    We can also use the GROUP BY statement on more than one column, like this:

    SELECT Customer,Date,SUM(Price) FROM Orders
    GROUP BY Customer,Date

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s