我不确定“group by”的目的是什么这里
我很难理解这个查询在做什么:
SELECT branch_name, count(distinct customer_name)
FROM depositor, account
WHERE depositor.account_number = account.account_number
GROUP BY branch_name
GROUP BY 需要什么?
I'm struggling to understand what this query is doing:
SELECT branch_name, count(distinct customer_name)
FROM depositor, account
WHERE depositor.account_number = account.account_number
GROUP BY branch_name
What's the need of GROUP BY?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须使用
GROUP BY
才能以这种方式使用COUNT
等聚合函数(使用聚合函数聚合与一个或多个值相对应的数据) em> 表内)。该查询本质上是使用该列作为分组列来选择不同的
branch_name
,然后在组内对不同的customer_name
进行计数。如果没有
GROUP BY
子句(至少不是使用简单的查询规范 - 您可以使用其他方式,连接,子查询等...)。You must use
GROUP BY
in order to use an aggregate function likeCOUNT
in this manner (using an aggregate function to aggregate data corresponding to one or more values within the table).The query essentially selects distinct
branch_name
s using that column as the grouping column, then within the group it counts the distinctcustomer_name
s.You couldn't use
COUNT
to get the number of distinctcustomer_name
s perbranch_name
without theGROUP BY
clause (at least not with a simple query specification - you can use other means, joins, subqueries etc...).它为您提供每个分支机构的不同客户总数;
GROUP BY
用于分组COUNT
函数。也可以写成:
It's giving you the total distinct customers for each branch;
GROUP BY
is used for groupingCOUNT
function.It could be written also as:
让我们暂时远离 SQL,看一下关系训练语言教程 D。
因为这两个关系(表)是在公共属性(列)名称
account_number
上连接的,所以我们可以使用自然连接:(因为结果是一个关系,根据定义它只有不同的元组(行) ),我们不需要
DISTINCT
关键字。)现在我们只需要使用
SUMMARIZE..BY
进行聚合:回到 SQLland,
GROUP BYbranch_name
的作用与SUMMARIZE..BY {branch_name}
相同。由于 SQL 具有非常严格的结构,因此branch_name
列必须在SELECT
子句中重复。Let's take a step away from SQL for a moment at look at the relational trainging language Tutorial D.
Because the two relations (tables) are joined on the common attribute (column) name
account_number
, we can use a natural join:(Because the result is a relation, which by definition has only distinct tuples (rows), we don't need a
DISTINCT
keyword.)Now we just need to aggregate using
SUMMARIZE..BY
:Back in SQLland, the
GROUP BY branch_name
is doing the same asSUMMARIZE..BY { branch_name }
. Because SQL has a very rigid structure, thebranch_name
column must be repeated in theSELECT
clause.如果您想要
COUNT
某些内容(请参阅SELECT
- 语句的一部分),则必须使用GROUP BY
来告诉查询什么聚合。 GROUP BY 语句与聚合函数结合使用,可按一列或多列对结果集进行分组。忽视它会导致大多数 RDBMS 中出现 SQL 错误,或者在其他 RDBMS 中导致毫无意义的结果。
有用的链接:
http://www.w3schools.com/sql/sql_groupby.asp
If you want to
COUNT
something (seeSELECT
-Part of the statement), you have to useGROUP BY
in order to tell the query what to aggregate. TheGROUP BY
statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.Neglecting it will lead to SQL errors in most RDBMS, or senseless results in others.
Useful link:
http://www.w3schools.com/sql/sql_groupby.asp