Table of Contents
1. 使用排序使数据有序?
2. 进行分组除去重复值?
3. 在分组之前进行数据筛选?
4. 返回所有分组?
5. 分组后筛选数据?
6. 进一步了解WHERE和HAVING语句?
7. 使用聚合函数统计分组数据?
8. 统计聚合数据?
9. 统计每个列?
10. 对统计结果排序?
Home Database Mysql Tutorial 最常用的SQL排序、分组与统计的使用方法

最常用的SQL排序、分组与统计的使用方法

Jun 07, 2016 pm 04:24 PM
sql Instructions Group sort Significant use statistics

以一种有意义的方式组织数据可能是一项挑战。有时你需要的可能是一个简单的排序,但是通常你需要做更多,你需要分组来进行分析和统计。幸运的是,SQL提供了大量语句和操作来进行排序,分组和摘要。下面的一些技巧将会帮助你识别什么时候排序,什么时候分组,

以一种有意义的方式组织数据可能是一项挑战。有时你需要的可能是一个简单的排序,但是通常你需要做更多,你需要分组来进行分析和统计。幸运的是,SQL提供了大量语句和操作来进行排序,分组和摘要。下面的一些技巧将会帮助你识别什么时候排序,什么时候分组,什么时候以及如何统计。对要每条语句和操作的详细信息请查看Books Online。?

1. 使用排序使数据有序?

通常,你的所有数据真正需要的仅仅是按某种顺序排列。SQL的ORDER BY语句可以以字母或数字顺序组织数据。因此,相似的值按组排序在一起。然而,这个分组时排序的结果,并不是真的分组。ORDER BY显示每条记录而分组可能代表很多记录。?

2. 进行分组除去重复值?

排序和分组之间的最大区别是:排序的数据显示所有记录(在限定标准范围之内),而分组数据不是显示所有记录。GROUP BY语句对于同样的值只显示一条记录。例如,下面的语句中的GROUP BY语句对数据源中重复出现的数据只返回唯一的zip编码列。?

SELECT ZIP FROM Customers GROUP BY ZIP 
Copy after login

只包括由GROUP BY和SELECT语句共同定义的那些记录,换句话说,SELECT列表必须满足GROUP BY列表,但是有一个例外就是SELECT列表可以包含聚合函数(GROUP BY语句不允许使用聚合函数)。需要注意的是GROUP BY语句不会对结果分组进行排序。为了使分组按字母或数字有序排列,需要添加ORDER BY语句。此外,在GROUP BY语句中不能引用使用了别名的字段。分组栏目必须是潜在的数据,但它们并不需要显示在结果中。?

3. 在分组之前进行数据筛选?

你可以添加一个WHERE语句来筛选有GROUP BY所得分组中的数据。例如,下面的语句只返回肯塔基州顾客的唯一ZIP编码列。?

SELECT ZIP FROM CustomersWHEREState = 'KY' GROUP BY ZIP 
Copy after login

必须注意的是WHERE语句是在GROUP BY语句求值之前进行数据过滤的。与GROUP BY语句一样,WHERE语句也不支持聚合函数。?

4. 返回所有分组?

当你使用WHERE语句过滤数据时,结果分组中只显示你指定的那些记录,而符合分组定义但是不满足过滤条件的数据不会包含在某个分组中。当你想在分组中包含所有数据时添加关键字ALL即可,这时WHERE条件就不起作用。例如,在前面的例子中添加关键字ALL就会返回所有的ZIP分组,而不是仅在肯塔基州的那些。?

SELECT ZIP FROM CustomersWHEREState = 'KY' GROUP BY ALL ZIP?
Copy after login

这样看来,这两个语句存在冲突,你可能不会以这种方式使用关键字ALL。当你使用聚合函数计算某一列时,使用ALL关键字可能会很方便。例如,下面的语句计算每个肯塔基州ZIP中的顾客数,同时,还会显示其它的ZIP值。?

SELECT ZIP, Count(ZIP) AS KYCustomersByZIP FROM?
CustomersWHEREState = 'KY' GROUP BY ALL ZIP?
Copy after login

结果分组包括潜在数据中的所有ZIP值,然而,对于那些不是肯塔基州ZIP分组的聚合列(KYCustomersByZIP)将会显示0。远程查询不支持GROUP BY ALL。?

5. 分组后筛选数据?

WHERE语句在GROUP BY语句之前进行计算。当你需要在分组之后筛选数据时,可以使用HAVING语句。通常情况下,WHERE语句和HAVING语句的返回结果是一样的,但是值得注意的是这两个语句不可互换。当你迷惑时,可以遵循下面的说明:使用WHERE语句过滤记录,使用HAVING语句过滤分组。?

一般情况,你会使用HAVING语句和某个聚合函数计算一个分组。例如,下面的语句返回一个唯一的ZIP编码列,但是可能不会包含潜在数据源中所有的ZIP。?

SELECT ZIP, Count(ZIP) AS CustomersByZIP FROM 

Customers GROUP BY ZIP HAVING Count(ZIP) = 1 
Copy after login

只有那些包含一位顾客的分组显示在结果中。?

6. 进一步了解WHERE和HAVING语句?

如果你对何时应该使用WHERE,何时使用HAVING仍旧很迷惑,请遵照下面的说明:

  • WHERE语句在GROUP BY语句之前;SQL会在分组之前计算WHERE语句。
  • HAVING语句在GROUP BY语句之后;SQL会在分组之后计算HAVING语句。?

7. 使用聚合函数统计分组数据?

分组数据可以帮助我们分析数据,但是有时我们可能需要更多的信息而不仅仅是分组。你可以使用聚合函数来统计分组数据。例如,下面的语句显示每批订购单的总价钱。?

SELECT OrderID, Sum(Cost * Quantity) AS OrderTotal 

FROM Orders GROUP BY OrderID 
Copy after login

对于其它的分组来说,SELECT和GROUP BY列必须匹配。而SELECT语句包含聚合函数时这一规则是一个例外。?

8. 统计聚合数据?

你可以继续统计数据为每个分组显示一个分类统计。SQL的ROLLUP操作符可以为每个分组显示一个额外的分类统计。这个分类统计是使用聚合函数计算每个分组中的所有记录得到的结果。下面的语句为每个分组计算OrderTotal:?

SELECT Customer, OrderNumber, Sum(Cost * Quantity) 

AS OrderTotal FROM Orders GROUP BY Customer, 

OrderNumber WITH ROLLUP 
Copy after login

对于有两个分别为20和25 OderTotal值的分组,ROLLUP显示一个OrderTotal值45。ROLLUP结果中的第一条记录是唯一的,因为它是计算所有分组记录,这个值是整个记录集的总值。?

ROLLUP在聚合函数中不支持 DISTINCT,也不支持GROUP BY ALL语句。

9. 统计每个列?

CUBE操作符比ROLLUP更进一步,它返回每个分组中重复值的个数。它的结果和ROLLUP相同,但是对每位客户的每一列CUBE包含一个额外的记录。下面的语句显示每个分组的统计和额外每位客户的统计。?

SELECT Customer, OrderNumber, Sum(Cost * Quantity) 

AS OrderTotal FROM Orders GROUP BY Customer, 

OrderNumber WITH CUBE 
Copy after login

CUBE可以给最综合的统计。它不仅完成聚合和ROLLUP的功能,还可以计算定义分组的其它列,换句话说,CUBE统计每个可能的列组合。?

CUBE不支持GROUP BY ALL语句。?

10. 对统计结果排序?

当CUBE的结果令人迷惑时(它经常是这样),可以添加一个GROUPING函数,如下所示:?

SELECT GROUPING(Customer), OrderNumber, 

Sum(Cost * Quantity) AS OrderTotal FROM Orders GROUP 

BY Customer, OrderNumber WITH CUBE 
Copy after login

结果中每行包含两个额外的值:?

  • 值1表示左边的值是一个统计值,是ROLLUP或CUBE的操作符。?
  • 值0表示左边的值是一条由最初的GROUP BY语句产生的详细记录。
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

How to use DirectX repair tool? Detailed usage of DirectX repair tool How to use DirectX repair tool? Detailed usage of DirectX repair tool Mar 15, 2024 am 08:31 AM

The DirectX repair tool is a professional system tool. Its main function is to detect the DirectX status of the current system. If an abnormality is found, it can be repaired directly. There may be many users who don’t know how to use the DirectX repair tool. Let’s take a look at the detailed tutorial below. 1. Use repair tool software to perform repair detection. 2. If it prompts that there is an abnormal problem in the C++ component after the repair is completed, please click the Cancel button, and then click the Tools menu bar. 3. Click the Options button, select the extension, and click the Start Extension button. 4. After the expansion is completed, re-detect and repair it. 5. If the problem is still not solved after the repair tool operation is completed, you can try to uninstall and reinstall the program that reported the error.

Usage of division operation in Oracle SQL Usage of division operation in Oracle SQL Mar 10, 2024 pm 03:06 PM

"Usage of Division Operation in OracleSQL" In OracleSQL, division operation is one of the common mathematical operations. During data query and processing, division operations can help us calculate the ratio between fields or derive the logical relationship between specific values. This article will introduce the usage of division operation in OracleSQL and provide specific code examples. 1. Two ways of division operations in OracleSQL In OracleSQL, division operations can be performed in two different ways.

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

How to use Baidu Netdisk-How to use Baidu Netdisk How to use Baidu Netdisk-How to use Baidu Netdisk Mar 04, 2024 pm 09:28 PM

Many friends still don’t know how to use Baidu Netdisk, so the editor will explain how to use Baidu Netdisk below. If you are in need, hurry up and take a look. I believe it will be helpful to everyone. Step 1: Log in directly after installing Baidu Netdisk (as shown in the picture); Step 2: Then select "My Sharing" and "Transfer List" according to the page prompts (as shown in the picture); Step 3: In "Friend Sharing", you can share pictures and files directly with friends (as shown in the picture); Step 4: Then select "Share" and then select computer files or network disk files (as shown in the picture); Fifth Step 1: Then you can find friends (as shown in the picture); Step 6: You can also find the functions you need in the "Function Treasure Box" (as shown in the picture). The above is the editor’s opinion

What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? Mar 18, 2024 am 11:07 AM

The KMS Activation Tool is a software tool used to activate Microsoft Windows and Office products. KMS is the abbreviation of KeyManagementService, which is key management service. The KMS activation tool simulates the functions of the KMS server so that the computer can connect to the virtual KMS server to activate Windows and Office products. The KMS activation tool is small in size and powerful in function. It can be permanently activated with one click. It can activate any version of the window system and any version of Office software without being connected to the Internet. It is currently the most successful and frequently updated Windows activation tool. Today I will introduce it Let me introduce to you the kms activation work

How to solve the 5120 error in SQL How to solve the 5120 error in SQL Mar 06, 2024 pm 04:33 PM

Solution: 1. Check whether the logged-in user has sufficient permissions to access or operate the database, and ensure that the user has the correct permissions; 2. Check whether the account of the SQL Server service has permission to access the specified file or folder, and ensure that the account Have sufficient permissions to read and write the file or folder; 3. Check whether the specified database file has been opened or locked by other processes, try to close or release the file, and rerun the query; 4. Try as administrator Run Management Studio as etc.

How to use potplayer-How to use potplayer How to use potplayer-How to use potplayer Mar 04, 2024 pm 06:10 PM

Potplayer is a very powerful media player, but many friends still don’t know how to use potplayer. Today I will introduce how to use potplayer in detail, hoping to help everyone. 1. PotPlayer shortcut keys. The default common shortcut keys for PotPlayer player are as follows: (1) Play/pause: space (2) Volume: mouse wheel, up and down arrow keys (3) forward/backward: left and right arrow keys (4) bookmark: P- Add bookmarks, H-view bookmarks (5) full screen/restore: Enter (6) multiple speeds: C-accelerate, 7) Previous/next frame: D/

See all articles