GROUP BY
GROUP BY is an SQL command used in conjunction with the aggregate functions to group the result-set by one or more columns. Its primary purpose is to arrange identical data into groups. It is typically used with the SELECT statement.
Example
Output
Explanation
In this example, the SQL statement groups the ‘employees’ table by the ‘department’ column, and it counts the number of records for each group. The output table therefore shows the number of employees in each department.
Example
Output
department | count |
---|---|
Sales | 100 |
HR | 50 |
IT | 150 |
Explanation
The above SQL statement groups records by the ‘department’ field in the ‘employees’ table and counts the number of records in each grouped category. The result displays the number of employees in each department.
Example
Output
Explanation
The above SQL statement is grouping the rows from the “Employees” table by the “Department” column. The COUNT(EmployeeID)
function is then used to count the number of employee IDs that appear within each department, effectively providing the total number of employees in each department. The as 'Number of Employees'
is used to alias the output column name to “Number of Employees”.
Example
Output
Explanation
In the provided SQL statement, the GROUP BY
clause is used to aggregate rows from the ‘employees’ table that have the same values in the ‘department_id’ column into groups. The COUNT(*)
function then counts the number of rows in each group. The output table shows the number of employees in each department.
Example
Output
Explanation
In the above example, GROUP BY
statement is used to group the customers based on their country. The COUNT(*)
function then counts the number of customers from each country.