REQUEST COMPLIMENTARY SQLS*PLUS LICENCE
SQL Server GROUP BY operator
SQL Server GROUP BY operator can be used in SELECT operator to collect data by several records and group results by one or more columns.
Syntax of GROUP BY statement in SQL
SELECT expr1, expr2, … expr_n,
aggregate_function (aggregate_expr)
FROM tab
[WHERE conds]
GROUP BY expr1, expr2, … expr_n
[ORDER BY expr [ ASC | DESC ]];
where:
- expr1,2, …_n – Expressions that are not encapsulated in the aggregate function and must be included in GROUP BY at the end of the SQL query.
- aggr_function – This is an aggregate function such as SUM, COUNT, MIN, MAX or AVG.
- aggr_expression – This is the column or expression for which aggregate_function will be used.
- tab – The tables from which you want the records. The FROM sentence must contain at least one table.
- WHERE conds – It’s optional. These are the conditions that must be met to select records.
- ORDER BY – It’s optional. The expression used to sort the records in the result set. If more than one expression is specified, the values must be separated by commas.
- ASC – It’s optional. ASC sorts the result set in ascending order by. This is the default behavior if no modifier is specified.
- DESC – It’s optional. DESC sorts the result set in descending order.
Using GROUP BY with SUM function
Let’s see how to use GROUP BY with SUM function in SQL.
In this example, we have a table with the following data:
emp_number | f_name | l_name | sal | dept |
---|---|---|---|---|
1001 | Justin | Bieber | 62000 | 500 |
1002 | Selena | Gomez | 57500 | 500 |
1003 | Mila | Kunis | 71000 | 501 |
1004 | Tom | Cruise | 42000 | 501 |
Enter the following SQL statement:
SELECT dept,
SUM(salary) AS total_sal
FROM employees
GROUP BY dept;
Two records will be selected. Here are the results that you will get:
dept | total_sal |
---|---|
500 | 119500 |
501 | 113000 |
In this example, we used the SUM function to add all the salaries for each dept, and we gave the nickname “total_sal” to the results of SUM(sal). Since dept is not encapsulated in the SUM function, it must be specified in the GROUP BY sentence.
Using GROUP BY with function COUNT
Let’s see how to use the GROUP BY offer with the COUNT function in SQL.
In this example, we have a product table with the following data:
prod_id | prod_name | cat_id |
---|---|---|
1 | Pear | 50 |
2 | Banana | 50 |
3 | Orange | 50 |
4 | Apple | 50 |
5 | Bread | 75 |
6 | Sliced Ham | 25 |
7 | Kleenex | NULL |
Enter the following SQL statement:
SELECT cat_id,
COUNT(*) AS total_prod
FROM prod
WHERE cat_id IS NOT NULL
GROUP BY cat_id
ORDER BY cat_id;
Three records will be selected. Here are the results that you should get:
cat_id | total_prod |
---|---|
25 | 1 |
50 | 4 |
75 | 1 |
In this example, we used the COUNT function to calculate the number of total_prod for each cat_id, and we specified the alias “total_prod” as the result of the COUNT function. We excluded all cat_id values that have a value of NULL and filtered them out in the WHERE sentence. Since cat_id is not encapsulated in the COUNT function, it must be specified in the GROUP BY sentence.
Using GROUP BY with function MIN
Let’s now look at how to use the GROUP BY offer with the MIN function in SQL.
In this example, we will again use the table with the following data:
emp_number | f_name | l_name | sal | dept |
---|---|---|---|---|
1001 | Justin | Bieber | 62000 | 500 |
1002 | Selena | Gomez | 57500 | 500 |
1003 | Mila | Kunis | 71000 | 501 |
1004 | Tom | Cruise | 42000 | 501 |
Enter the following SQL statement:
SELECT dept,
MIN(sal) AS lowest_sal
FROM empl
GROUP BY dept;
Two records will be selected. Here are the results that you will get:
dept | low_sal |
---|---|
500 | 57500 |
501 | 42000 |
In this example, we used the MIN function to return the minimum salary for each dept, and we assigned the results to the MIN function <a> alias “low_sal”. Since dept is not encapsulated in the MIN function, it must be specified in the GROUP BY sentence.
Using GROUP BY with the MAX function
Finally, let’s look at how to use the GROUP BY offer with the MAX feature.
Let’s use the employees table again, but this time we will find the highest salary for each dept_id:
emp_number | f_name | l_name | sal | dept |
---|---|---|---|---|
1001 | Justin | Bieber | 62000 | 500 |
1002 | Selena | Gomez | 57500 | 500 |
1003 | Mila | Kunis | 71000 | 501 |
1004 | Tom | Cruise | 42000 | 501 |
Enter the following SQL statement:
SELECT dept,
MAX(sal) AS highest_sal
FROM empl
GROUP BY dept;
Two records will be selected. Here are the results that you should get:
dept | high_sal |
---|---|
500 | 62000 |
501 | 71000 |
In this example, we used the MAX function to return the maximum salary value for each dept, and we assigned the alias “high_salary” to the result of the MAX function. The dept column must be specified in the GROUP BY clause since it is not encapsulated in the MAX function.
More Examples:
All examples will be on this table unless otherwise stated:
f_id | f_name | f_age | f_sal |
---|---|---|---|
1 | Justin | 23 | 100 |
2 | Selena | 23 | 200 |
3 | Mila | 23 | 300 |
4 | Tom | 24 | 1000 |
5 | Christian | 24 | 2000 |
6 | Daniel | 25 | 1000 |
Example №1
In this example the records are grouped by age (there will be 3 groups – 23 years, 24 years and 25 years). Then for each group the sum function is applied, which sums up the wages within that group.
As a result, for each of the groups (23 years, 24 years and 25 years) the total salaries within this group will be calculated:
SELECT f_age, SUM(f_sal) as sum FROM workers_1 GROUP BY f_age
The SQL query will select the following lines:
f_age | sum |
---|---|
23 | 600 |
24 | 3000 |
25 | 1000 |
Example №2
In this example, we use the additional condition where to take not all entries from the table:
SELECT f_age, SUM(f_sal) as sum FROM workers_1 WHERE id>=2 GROUP BY f_age
The SQL query will select the following lines:
f_age | sum |
---|---|
23 | 500 |
24 | 3000 |
25 | 1000 |
Example №3
In this example the records are grouped by age (there will be 3 groups – 23 years, 24 years and 25 years). Then for each group the function max is applied, which finds the maximum salary within this group:
SELECT f_age, MAX(f_sal) as max FROM workers_1 GROUP BY f_age
The SQL query will select the following lines:
f_age | max sal |
---|---|
23 | 300 |
24 | 2000 |
25 | 1000 |
Example №4
And now with the help of the min function we will find the minimum wage within this group:
SELECT f_age, MIN(f_sal) as min FROM workers_1 GROUP BY f_age
The SQL query will select the following lines:
f_age | min sal |
---|---|
23 | 100 |
24 | 1000 |
25 | 1000 |
Example №5
And now with the help of the count function you will find the number of records in the group:
SELECT f_age, COUNT(*) as count FROM workers_1 GROUP BY f_age
The SQL query will select the following lines:
f_age | count |
---|---|
23 | 3 |
24 | 2 |
25 | 1 |
Understanding the use of GROUP BY clause in SQL
MORE NEWS
PreambleNoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...
PreambleMongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...
5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...
The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...
PreambleMS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...
First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...
PreambleAtom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...
PreambleMongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...
FlexibilityOne of the most advertised features of MongoDB is its flexibility. Flexibility, however, is a double-edged sword. More flexibility means more...
PreambleSQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...
PreambleWriting an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...
PreambleOracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...
PreambleIBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...
What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....
PreambleIf you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...
PreambleStarting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...