gpt4 book ai didi

sql - 如何从集合的角度考虑聚合函数

转载 作者:行者123 更新时间:2023-11-29 07:15:37 25 4
gpt4 key购买 nike

我试图从集合的角度来思考数据,但对聚合函数有一些疑问。

这是wiki上的定义

an aggregate function is a function that returns a single value from a collection of input values such as a set

例如,

select c.id, c.user_id, c.name, c.created_at, count(c.id) from collections c;

可以认为是“count从集合c集合返回单个值”

select c.id, c.user_id, c.name, c.created_at, count(c.id) 
from collections c group by c.user_id

可以认为是“count 从集合(c) 集合的每个子集(从group by 中设置)返回单个值”

我的问题是,我如何知道计数返回的是哪个“单个值”,在本例中是 collection(c) 集或每个“分组依据”子集。

考虑一个稍微复杂的查询(每组前 N 个)

select c.id, c.user_id, c.name, c.created_at 
from collections c
left join collections co on c.user_id = co.user_id and c.name <=co.name
group by c.user_id, c.name
having count(*)<=2;

这里的 sets group by(c.user_id) 有自己的子集(c.name),我怎么知道 count(*) 会返回什么(整个集合的单个值(这只是一个rol)? 或每个子集的单个值(c.user_id) 或每个子集的单个值(c.name)?)

最佳答案

对于执行聚合的任何查询,您需要按正确的字段进行分组。

第一个查询应该会失败,因为 c.id、c.user_id、c.name 和 c.created_at 字段未使用 GROUP BY 进行分组。

同样,第二个查询也会失败,因为只有第一个字段被分组。

要使最后一个查询生效,您可能还需要在 GROUP BY 中包含 id。

聚合函数仅在 SELECT 子句的所有非聚合元素(例如 c.id、c.user_id 等)代表正在聚合的组(即包含在 GROUP BY 子句中)时才起作用。

关于sql - 如何从集合的角度考虑聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1391588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com