T Sql 简明教程

T-SQL - GROUP BY Clause

SQL Server GROUP BY 子句与 SELECT 语句配合使用,将相同数据整理到组中。

The SQL Server GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.

GROUP BY 子句在 SELECT 语句中紧跟在 WHERE 子句之后,并且出现在 ORDER BY 子句之前。

The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax

以下是 GROUP BY 子句的基本语法。GROUP BY 子句必须跟在 WHERE 子句的条件之后,如果使用,则必须在 ORDER BY 子句之前。

Following is the basic syntax of GROUP BY clause. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

Example

考虑 CUSTOMERS 表具有以下记录 −

Consider the CUSTOMERS table is having the following records −

ID  NAME       AGE       ADDRESS          SALARY
1   Ramesh     32        Ahmedabad        2000.00
2   Khilan     25        Delhi            1500.00
3   kaushik    23        Kota             2000.00
4   Chaitali   25        Mumbai           6500.00
5   Hardik     27        Bhopal           8500.00
6   Komal      22        MP               4500.00
7   Muffy      24        Indore           10000.00

如果您想了解每个客户的工资总额,那么以下将是 GROUP BY 查询。

If you want to know the total amount of salary on each customer, then following will be the GROUP BY query.

SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS
   GROUP BY NAME;

以上命令将生成以下输出。

The above command will produce the following output.

NAME        sum of salary
Chaitali    6500.00
Hardik      8500.00
kaushik     2000.00
Khilan      1500.00
Komal       4500.00
Muffy       10000.00
Ramesh      2000.00

现在让我们考虑以下 CUSTOMERS 表,其中有以下记录,带有重复姓名。

Let us now consider the following CUSTOMERS table having the following records with duplicate names.

ID  NAME       AGE       ADDRESS           SALARY
1   Ramesh     32        Ahmedabad         2000.00
2   Khilan     25        Delhi             1500.00
3   kaushik    23        Kota              2000.00
4   Chaitali   25        Mumbai            6500.00
5   Hardik     27        Bhopal            8500.00
6   Komal      22        MP                4500.00
7   Muffy      24        Indore            10000.00

如果您想了解每个客户的工资总额,那么以下将是 GROUP BY 查询。

If we want to know the total amount of salary on each customer, then following will be GROUP BY query.

SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS
   GROUP BY NAME

以上命令将生成以下输出。

The above command will produce the following output.

NAME        sum of salary
Hardik      8500.00
kaushik     8500.00
Komal       4500.00
Muffy       10000.00
Ramesh      3500.00