是否可以在 Select 语句中使用 Aggregate 函数而不使用 Group By 子句?

到目前为止,我已经编写了聚合函数,然后是 Group By 子句,以查找基于 SUM、AVG 和其他聚合函数的值.我对 Group By 子句有点困惑.当我们使用聚合函数时,我需要在 Group By 子句中指定哪些列.否则有什么方法可以不使用 Group By 子句来使用聚合函数.

So far I have written Aggregate function followed by Group By clause to find the values based on SUM, AVG and other Aggregate functions. I have a bit confusion in the Group By clause. When we use Aggregate functions what are the columns I need to specify in the Group By clause. Otherwise Is there any way to use Aggregate functions without using Group By clause.

推荐答案

SELECT 子句中所有没有聚合的列都需要在 GROUP BY 中

All columns in the SELECT clause that do not have an aggregate need to be in the GROUP BY

好:

SELECT col1, col2, col3, MAX(col4)
...
GROUP BY col1, col2, col3

也不错:

SELECT col1, col2, col3, MAX(col4)
...
GROUP BY col1, col2, col3, col5, col6

没有其他列 = 不需要 GROUP BY

No other columns = no GROUP BY needed

SELECT MAX(col4)
...

不起作用:

SELECT col1, col2, col3, MAX(col4)
...
GROUP BY col1, col2

毫无意义:

SELECT col1, col2, col3, MAX(col4)
...
GROUP BY col1, col2, col3, MAX(col4)

在没有 GROUP BY 的情况下对其他列进行聚合(MAX 等)是没有意义的,因为查询变得不明确.

Having an aggregate (MAX etc) with other columns without a GROUP BY makes no sense because the query becomes ambiguous.

相关文章