Get the App
SLTechnology News&Howtos  ›  Servers  › 

What is the use of GROUP BY in SQL

Shulou Source: shulou.com Published: 2022-05-31 23:15:53 10月01日 Update

Editor to share with you what is the use of GROUP BY in SQL, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

In SQL, GROUP BY refers to cutting the total data table into several sub-data tables, and then processing each sub-data table, for example, we need to calculate the number of people in each grade in the following table.

Gradenamescore first grade Xiao Wang 51 first grade Xiao Wei 61 first grade Xiao Zhang 71 first grade Xiao Li 51 first grade Xiao Wang 51 second grade middle Wang 51 second grade middle Wei 61 second grade Zhang 71 second grade middle Li 51 third grade Wang 51 third grade Dawei 61 third grade Da Zhang 71 third grade Da Li 51 third grade Wang 51

Enter SQL statement

SELECT grade total,COUNT (name) AS total FROM tbl GROUP BY grade

The query results after entering the SQL statement are listed in the following table:

Gradetotal Grade 1 Grade 5 Grade 3 Grade 5 Grade 2 Grade 5

Let's take a detailed look at the specific implementation process, as shown in the following figure

First, SQL splits the total data table according to GROUP BY (press "grade") and divides it into three sub-tables.

The "name" field of each subtable is then COUNT AS (total) calculated, and then merged to generate the final data.

By the same token, we can also calculate the average score of each grade.

Enter SQL statement

SELECT grade total,avg (score) as avg FROM tbl GROUP BY grade

Result

Gradeavg Grade 1 57 Grade 3 57 Grade 2 57

The specific process, as shown in the figure

The above is all the content of this article "what is the use of GROUP BY in SQL?" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Grade data datasheet size article sentence input content king result table process Xiao Wang middle king not so many number most field average more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi macOS MariaDB Apple MySQL