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.
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 .
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 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With