Home > Database > SQL > Group by usage in sql

Group by usage in sql

下次还敢
Release: 2024-05-01 23:18:52
Original
579 people have browsed it

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>
Copy after login

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>
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template