SQL > SQL Commands > Having

Another thing people may want to do is to limit the output based on the corresponding sum (or any other aggregate functions). For example, we might want to see only the stores with sales over $1,500. Instead of using the WHERE clause in the SQL statement, though, we need to use the HAVING clause, which is reserved for aggregate functions. The HAVING clause is typically placed near the end of the SQL statement, and a SQL statement with the HAVING clause may or may not include the GROUP BY clause. The syntax for HAVING is,

SELECT ["column_name1"], Function("column_name2")
FROM "table_name"
[GROUP BY "column_name1"]
HAVING (arithmetic function condition);

Note: We may select zero, one, or more columns in addition to the aggregate function. If we select zero column, there is no need for the GROUP BY clause.

In our example, table Store_Information,

Table Store_Information

Store_NameSalesTxn_Date
Los Angeles1500Jan-05-1999
San Diego250Jan-07-1999
Los Angeles300Jan-08-1999
Boston700Jan-08-1999

we would type,

SELECT Store_Name, SUM(Sales)
FROM Store_Information
GROUP BY Store_Name
HAVING SUM(Sales) > 1500;

Result:

Store_NameSUM(Sales)
Los Angeles1800

Exercises

For these exercises, assume we have a table called Region_Sales with the following data:

Table Region_Sales

RegionYearOrdersTotal_Sales
West20131560325000
West20141820380000
North2013790148000
North2014995185000
East20131760375000
East20142220450000
South20131790388000
South20141695360000

1. Which of the following order is correct for a SQL statement?
a) SELECT...FROM...ORDER BY...WHERE...HAVING
b) SELECT...FROM...WHERE...ORDER BY...HAVING
c) SELECT...WHERE...FROM...HAVING...ORDER BY
d) SELECT...FROM...WHERE...HAVING...ORDER BY

2. What is the result of the following SQL statement?
SELECT Region, SUM(Orders) FROM Region_Sales GROUP BY Region HAVING SUM(Orders) > 2500;

3. What is the result of the following SQL statement?
SELECT Region, SUM(Orders) FROM Region_Sales WHERE Total_Sales < 385000 GROUP BY Region HAVING SUM(Orders) > 2500;

Next: SQL Alias




Copyright © 2015   1keydata.com   All Rights Reserved.     Privacy Policy     About   Contact