简体   繁体   English

与GROUP BY一起使用时COUNT(DISTINCT ..)的范围

[英]Scope of COUNT(DISTINCT ..) when used with GROUP BY

I'm doing something like follows (Example, getting distinct people named "Mark" by State): 我正在执行以下操作(例如,按州划分名为“ Mark”的不同人员):

Select count(distinct FirstName) FROM table
GROUP BY State

I think the group by query organization is done first, such that the distinct is only relative to each "group by"? 认为按查询组织分组是首先完成的,这样唯一的区别就是相对于每个“分组依据”吗? Basically, can "Mark" show up as a "distinct" count in each group? 基本上,“标记”是否可以在每个组中显示为“不同”计数? This would "scope" my distinct expression to the group by rows only, I believe... 我相信,这只会将我独特的表达“按范围”仅按组显示。

This may actually depend on where DISTINCT is used. 这实际上可能取决于使用DISTINCT位置。 For example, SELECT DISTINCT COUNT( would be different than SELECT COUNT(DISTINCT . 例如, SELECT DISTINCT COUNT(将不同于SELECT COUNT(DISTINCT

In this case, it will work as you want and get a count of distinct names in each group (even if the names are not distinct across groups). 在这种情况下,它将按您希望的方式工作,并在每个组中获得不同名称的计数(即使名称在各组之间不是不同的)。

Your understanding is correct. 您的理解是正确的。 Group by says, essentially, to take a group of rows and aggregate them into one row (based on the criteria). Group by实际上是指将一组行合并为一行(基于条件)。 All aggregation functions -- including count(distinct) -- summarize values in this group. 所有聚合函数-包括count(distinct) -汇总该组中的值。

As a note, you are using the word "scope". 注意,您使用的是“范围”一词。 Just so you know, this has a particular meaning in SQL. 众所周知,这在SQL中具有特殊的含义。 The meaning refers to the portions of the query where a column or table alias are understood by the compiler. 含义是指查询的其中编译器可以理解列或表别名的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM