Dear readers of our blog, we'd like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.
 
SQLS*Plus - best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.
 

REQUEST COMPLIMENTARY SQLS*PLUS LICENCE

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

SQL Server GROUP BY operator

26 June 2020

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_numberf_namel_namesaldept
1001JustinBieber62000500
1002SelenaGomez57500500
1003MilaKunis71000501
1004TomCruise42000501

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:

depttotal_sal
500119500
501113000

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_idprod_namecat_id
1Pear50
2Banana50
3Orange50
4Apple50
5Bread75
6Sliced Ham25
7KleenexNULL

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_idtotal_prod
251
504
751

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_numberf_namel_namesaldept
1001JustinBieber62000500
1002SelenaGomez57500500
1003MilaKunis71000501
1004TomCruise42000501

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:

deptlow_sal
50057500
50142000

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_numberf_namel_namesaldept
1001JustinBieber62000500
1002SelenaGomez57500500
1003MilaKunis71000501
1004TomCruise42000501

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:

depthigh_sal
50062000
50171000

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_idf_namef_agef_sal
1Justin23100
2Selena23200
3Mila23300
4Tom241000
5Christian242000
6Daniel251000

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_agesum
23600
243000
251000

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_agesum
23500
243000
251000

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_agemax sal
23300
242000
251000

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_agemin sal
23100
241000
251000

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_agecount
233
242
251

Understanding the use of GROUP BY clause in SQL

 
Tags: , , ,

MORE NEWS

 

Preamble​​NoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...

Preamble​​MongoDB 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...

Preamble​​MS 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...

Preamble​​Atom 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...

Preamble​​MongoDB 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...

Preamble​​SQLShell 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...

Preamble​​Writing 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...

Preamble​​Oracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...

Preamble​​IBM 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....

Preamble​​If 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...

Preamble​​Starting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...