SQL GROUP BY
SQL > SQL Commands >
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")
GROUP BY "column_name1";
Let's illustrate using the following table,
We want to find total sales for each store. To do so, we would key in,
SELECT Store_Name, SUM(Sales)
GROUP BY Store_Name;
GROUP BY Multiple Columns
In this example, there is only one column associated with GROUP BY. It is possible to have two columns or more associated with GROUP BY.
The GROUP BY keyword is used when we are selecting multiple columns from a table (or tables) and at least one arithmetic operator appears in the SELECT statement. Such operators include COUNT, SUM, MAX, MIN, and AVG. 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 arithmetic operator. As such, it is important to note that we may have two columns or more associated with GROUP BY. The general syntax is as follows:
SELECT "column_name1", "column_name2", ... "column_nameN", Function("column_nameN+1")
GROUP BY "column_name1", "column_name2", ... "column_nameN";
GROUP BY Month / Date / Week
A common use of the GROUP BY function is on a time period, which can be month, week, day, or even hour. This type of query is often combined with the ORDER BY keyword to provide a query result that shows a time series.
For example, to find total daily sales from Store_Information, we use the following SQL:
SELECT Txn_Date, SUM(Sales)
GROUP BY Txn_Date;
For these exercises, assume we have a table called Region_Sales with the following data:
1. Which of the following order is correct for a SQL statement?
2. Write a SQL statement that calculates the total dollar sales amount for each region. What is the result?
3. Write a SQL statement that calculates the average annual dollar sales amount for just the East region and the West region. What is the result?