sql中聚合函数和分组函数_学习SQL:聚合函数

sql中聚合函数和分组函数

SQL has many cool features and aggregate functions are definitely one of these features, actually functions. While they are not specific to SQL, they are used often. They are part of the SELECT statement, and this allows us to have all benefits of SELECT (joining tables, filtering only rows and columns we need), combined with the power of these functions.

SQL具有许多很酷的功能,聚合函数绝对是这些功能之一,实际上是函数。 尽管它们不特定于SQL,但经常使用。 它们是SELECT语句的一部分,这使我们能够充分利用SELECT的所有好处(联接表,仅过滤所需的行和列),并结合这些功能的强大功能。

该模型 (The Model)

Before we start talking about aggregate functions, we’ll shortly comment on the data model we’ll be using.

在开始讨论聚合函数之前,我们将简短地评论将要使用的数据模型。

sql中聚合函数和分组函数_学习SQL:聚合函数_第1张图片

This is the same model we’ve been using in a few past articles. I won’t go into details, but rather mention that all 6 tables in the model contain data. Some of the records in tables are referenced in others, while some are not. E.g. we have countries without any related city, and we have cities without any related customers. We’ll comment on this in the article where it will be important.

这与我们在过去的几篇文章中一直使用的模型相同。 我不会详细介绍,而是要提到模型中的所有6个表都包含数据。 表中的某些记录在其他表中被引用,而另一些则没有。 例如,我们有没有任何相关城市的国家,而我们有没有任何相关客户的城市。 我们将在文章中对此进行评论,这将是重要的。

最简单的集合函数 (The Simplest Aggregate Function)

We’ll, of course, start with the simplest possible aggregate function. But, before we do it, let’s check the contents of the two tables we’ll use throughout this article. There are tables country and city. We’ll use the following statements:

当然,我们将从最简单的聚合函数开始。 但是,在进行此操作之前,让我们检查一下我们将在本文中使用的两个表的内容。 有桌子国家城市 。 我们将使用以下语句:

SELECT *
FROM country;
 
SELECT *
FROM city;

You can see the result in the picture below:

您可以在下图中看到结果:

sql中聚合函数和分组函数_学习SQL:聚合函数_第2张图片

This is nothing new and unexpected. We’ve just listed everything that is in our tables ( “*” in the query will result in returning all columns/attributes, while the lack of any condition/WHERE part of the query will result in returning all rows).

这并不是什么新鲜事和意外的事情。 我们刚刚列出了表中的所有内容(查询中的“ *”将导致返回所有列/属性,而查询中缺少任何条件/ WHERE部分将导致返回所有行)。

The only thing I would like to point out is that the country table has 7 rows and that the city table has 6 rows. Now, let’s examine the following queries and their result:

我唯一要指出的是, 国家表有7行, 城市表有6行。 现在,让我们检查以下查询及其结果:

sql中聚合函数和分组函数_学习SQL:聚合函数_第3张图片

We can notice that for each query we got one row as a result, and the number returned represents the number of rows in each of these two tables. That’s what aggregate function COUNT does. It takes what the query without COUNT would return, and then returns the number of rows in that result. One more important thing you should be aware of is that only COUNT can be used with “*”. All other functions shall require an attribute (or formula) between brackets. We’ll see that later.

我们可以注意到,对于每个查询,结果只有一行,返

你可能感兴趣的:(数据库,python,java,大数据,mysql)