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.
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- What is the best way to cache a table from a (SQL)
- php PDO::FETCH_ASSOC doesnt detect select after ba
Yes you can use an aggregate without GROUP BY:
This will return one row only - the sum of the column "col" for all rows in tbl (excluding nulls).
You must group by columns that do not have aggregate functions on them.
You may avoid a group by clause if all columns selected have aggregate functions applied.
You can use Select AGG() OVER() in TSQL
There are other options for Over such as Partition By if you want to group:
http://msdn.microsoft.com/en-us/library/ms189461.aspx
The Columns which are not present in the Aggregate function should come on group by clause:
then we do not required group by clause, But if there is some column which are not present in the Aggregate function then you must use group by for that column.
then we have to use the group by for the column col1 and col2
All columns in the SELECT clause that do not have an aggregate need to be in the GROUP BY
Good:
Also good:
No other columns = no GROUP BY needed
Won't work:
Pointless:
Having an aggregate (MAX etc) with other columns without a GROUP BY makes no sense because the query becomes ambiguous.
You omit columns from the SELECT inside aggregate functions, all other columns should exist in GROUP BY clause seperated by comma.
You can have query with aggregates and no group by, as long as you have ONLY aggregate values in the SELECT statement