简体   繁体   English

在SQL中使用GROUP BY - 仅限聚合?

[英]Use of GROUP BY in SQL — only with aggregates?

is GROUP BY used only with aggregate functions ? GROUP BY仅用于聚合函数吗? Can anyone give an example where it is used not in conjunction with aggregate functions. 任何人都可以举例说明它不与聚合函数一起使用。

SELECT with GROUP BY can be used as an alternative to SELECT DISTINCT. SELECT BY GROUP BY可用作SELECT DISTINCT的替代方法。 Pranay Rana's example is essentially equivalent to Pranay Rana的例子基本上相当于

SELECT DISTINCT UserName, Departmentid FROM user

If you want an example where the preference of GROUP BY over DISTINCT is justified, here's one. 如果你想要一个例子,其中GROUP BY优先于DISTINCT是合理的,这里是一个。 Say, you want to return items that only occur once in a table: 比如说,您想要返回仅在表中出现一次的项目:

SELECT Item
FROM atable
GROUP BY Item
HAVING COUNT(*) = 1

As you can see, the query only returns a non-aggregated column. 如您所见,查询仅返回非聚合列。

It still uses an aggregate function, though, even if not in the SELECT clause. 尽管如此,它仍然使用聚合函数,即使不在SELECT子句中也是如此。 There may be situations where you must prefer GROUP BY to DISTINCT while not needing to use aggregate functions at all , but I'll have to be platform specific at this point. 可能是,你必须喜欢GROUP BY到DISTINCT,同时不需要在所有使用聚合函数的情况,但我必须要具体在这一点上平台。

In particular, if you are using SQL Server, you will find a difference between the results of the following two statements: 特别是,如果您使用的是SQL Server,您会发现以下两个语句的结果之间存在差异:

#1: #1:

WITH data (f) AS (
  SELECT 'abc' UNION ALL
  SELECT 'def' UNION ALL
  SELECT 'abc'
)
SELECT f, ROW_NUMBER() OVER (ORDER BY f) FROM data GROUP BY f

#2: #2:

WITH data (f) AS (
  SELECT 'abc' UNION ALL
  SELECT 'def' UNION ALL
  SELECT 'abc'
)
SELECT DISTINCT f, ROW_NUMBER() OVER (ORDER BY f) FROM data

(If you aren't, you can still see the results for yourself using Stack Exchange Data Explorer .) (如果不是,您仍然可以使用Stack Exchange Data Explorer自行查看结果。)

Both statements are meant to return distinct items ranked. 这两个语句都是为了返回排名的不同项目。 However, only the first statement (with GROUP BY) returns the results as expected, while the latter (with DISTINCT) returns all items. 但是,只有第一个语句(使用GROUP BY)按预期返回结果,而后者(使用DISTINCT)返回所有项目。 Obviously, ranking functions in SQL Server are evaluated after GROUP BY, but before DISTINCT The reason is, the SELECT clause in SQL Server is evaluated after GROUP BY, but before DISTINCT, which makes you prefer GROUP BY over DISTINCT in this case. 显然,SQL Server中的排名函数是在GROUP BY之后但在DISTINCT之前评估的原因是, SQL Server中的SELECT子句是在GROUP BY之后但在DISTINCT之前评估的,这使得在这种情况下你更喜欢GROUP BY而不是DISTINCT。 (Thanks @ypercube for nudging me in the right direction.) (感谢@ypercube向我推进正确的方向。)

我没有应用任何聚合函数的东西

Select City,State from geodata group by City,State

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

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