Home  >  Article  >  Database  >  Group by usage in sql

Group by usage in sql

下次还敢
下次还敢Original
2024-05-01 23:18:52531browse

The GROUP BY statement in SQL groups the data set by specified columns and performs aggregate calculations on each group. Usage is as follows: Identify grouping columns: Specify the columns to be grouped. Aggregation functions: Use SUM, COUNT, AVG and other functions to calculate grouped values. Grouped results: The query returns grouped results, showing the aggregated calculated value of each group.

Group by usage in sql

GROUP BY Usage in SQL

The GROUP BY statement in SQL is used to group rows in a data set , and aggregate the data according to the grouping. It works by grouping rows that have the same value for a specific column.

Basic syntax:

<code class="sql">SELECT aggregate_function(column_name)
FROM table_name
GROUP BY column_name</code>

Usage:

  1. Identifying grouping columns: Usage The GROUP BY clause specifies the columns to be grouped.
  2. Aggregation functions: Use aggregate functions (such as SUM, COUNT, AVG) to calculate values ​​in grouped columns.
  3. Group results: The query returns grouped results, where each row represents a group and displays the aggregate calculation results.

Example:

Suppose we have a table containing student grades:

##3John 954Susan80
Student number Name Achievements
1 John 85
2 Mary 90
The following query sorts student scores by name Group and calculate the average of each student's score:

<code class="sql">SELECT AVG(成绩)
FROM students
GROUP BY 姓名</code>
Result:

##NameJohnMarySusan
Average score
90
90
80
Note:

The values ​​in the grouping column must Have equal data types.
  • The GROUP BY clause must come after the FROM clause and before the HAVING clause.
  • HAVING clause can be used to further filter the grouped results.

The above is the detailed content of Group by usage in sql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use groupby in sqlNext article:How to use groupby in sql