Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use Aggregate function in a Select statment without using Group By clause?

Tags:

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.

like image 818
thevan Avatar asked Jun 24 '11 11:06

thevan


People also ask

Does aggregate function need GROUP BY?

If you don't specify GROUP BY , aggregate functions operate over all the records selected. In that case, it doesn't make sense to also select a specific column like EmployeeID .

Can we use aggregate function in select clause?

An aggregate function performs a calculation on a set of values, and returns a single value. Except for COUNT(*) , aggregate functions ignore null values. Aggregate functions are often used with the GROUP BY clause of the SELECT statement.

Which functions can be used without a GROUP BY clause?

Which of the following functions can be used without GROUP BY clause in SELECT query? Answer: A, B, C, D. All the listed group functions can be used in a query provided no other columns are selected in the SELECT query.

Can aggregate functions be used with HAVING but not GROUP BY?

Aggregate functions can be used only in the select list or in a having clause. They cannot be used in a where or group by clause. Aggregate functions are of two types. Aggregates applied to all the qualifying rows in a table (producing a single value for the whole table per function) are called scalar aggregates.


2 Answers

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

Good:

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

Also good:

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

No other columns = no GROUP BY needed

SELECT MAX(col4) ... 

Won't work:

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

Pointless:

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

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

like image 156
gbn Avatar answered Oct 20 '22 11:10

gbn


You can use Select AGG() OVER() in TSQL

SELECT *, SUM(Value) OVER() FROM Table 

There are other options for Over such as Partition By if you want to group:

SELECT *, SUM(Value) OVER(PARTITION By ParentId) FROM Table 

http://msdn.microsoft.com/en-us/library/ms189461.aspx

like image 26
Anthony Sottile Avatar answered Oct 20 '22 12:10

Anthony Sottile