Thursday, April 28, 2016

GROUP BY CLAUSE

This SQL tutorial explains how to use the SQL GROUP BY clause with syntax and examples.

DESCRIPTION

The SQL GROUP BY clause can be used in a SELECT statement to collect data across multiple records and group the results by one or more columns.

SYNTAX

The syntax for the SQL GROUP BY clause is:
SELECT expression1, expression2, ... expression_n, 
       aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Parameters or Arguments

expression1, expression2, ... expression_n
Expressions that are not encapsulated within an aggregate function and must be included in the GROUP BY Clause at the end of the SQL statement.
aggregate_function
This is an aggregate function such as the SUMCOUNTMINMAX, or AVG functions.
aggregate_expression
This is the column or expression that the aggregate_function will be used on.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.

EXAMPLE - USING SUM FUNCTION

Let's look at a SQL GROUP BY query example that uses the SQL SUM function.
This GROUP BY example uses the SUM function to return the name of the department and the total sales (for the department).
SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;
Because you have listed one column (the department field) in your SQL SELECT statement that is not encapsulated in the SUM function, you must use the GROUP BY Clause. The department field must, therefore, be listed in the GROUP BY clause.

EXAMPLE - USING COUNT FUNCTION

Let's look at how we could use the GROUP BY clause with the SQL COUNT function.
This GROUP BY example uses the COUNT function to return the department and the number of employees (in the department) that make over $25,000 / year.
SELECT department, COUNT(*) AS "Number of employees"
FROM employees
WHERE salary > 25000
GROUP BY department;

EXAMPLE - USING MIN FUNCTION

Let's next look at how we could use the GROUP BY clause with the SQL MIN function.
This GROUP BY example uses the MIN function to return the name of each department and the minimum salary in the department.
SELECT department, MIN(salary) AS "Lowest salary"
FROM employees
GROUP BY department;

EXAMPLE - USING MAX FUNCTION

Finally, let's look at how we could use the GROUP BY clause with the SQL MAX function.
This GROUP BY example uses the MAX function to return the name of each department and the maximum salary in the department.
SELECT department, MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;

No comments:

Post a Comment