SQL Tutorial


SQL SELECT
SQL DISTINCT
SQL WHERE
SQL AND OR
SQL IN
SQL BETWEEN
SQL LIKE
SQL ORDER BY
SQL Functions
SQL COUNT
SQL GROUP BY
SQL HAVING
SQL ALIAS
SQL JOIN
SQL OUTER JOIN
SQL Subquery
SQL UNION
SQL UNION ALL
SQL INTERSECT
SQL MINUS














Data Warehousing & Business Intelligence
Area Codes Info
State Info
HTML Tutorial























Home
SQL Commands
Table Manipulation
SQL Syntax

SQL GROUP BY

Now we return to the aggregate functions. Remember we used the SUM keyword to calculate the total sales for all stores? What if we want to calculate the total sales for each store? Well, we need to do two things: First, we need to make sure we select the store name as well as total sales. Second, we need to make sure that all the sales figures are grouped by stores. The corresponding SQL syntax is,

SELECT "column_name1", SUM("column_name2")
FROM "table_name"
GROUP BY "column_name1"

In our example, table Store_Information,

Table Store_Information
store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999

we would key in,

SELECT store_name, SUM(Sales)
FROM Store_Information
GROUP BY store_name

Result:

store_nameSUM(Sales)
Los Angeles$1800
San Diego$250
Boston$700

The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at least one arithematic operator appears in the SELECT statement. When that happens, we need to GROUP BY all the other selected columns, i.e., all columns except the one(s) operated on by the arithematic operator.

Next Section

Site Map   |   Resources

1