Group By:
In SQL Server we have got lot of aggregate functions. Likes:
1. Count()
2. Sum()
3. avg()
4. Min()
5. Max()
Group by
clause is used to group a selected set of rows into a set of summary
rows by the values of one or more columns or expressions. It is always used in conjunction with one or more aggregate functions.
Syntax look likes : SELECT COUNT(Column name), column name1
FROM table name
GROUP BY column name1;
Filtering Groups:
WHERE clause is
used to filter rows before aggregation, where as HAVING clause is used
to filter groups after aggregations. The following 2 queries produce the same result.
Filtering rows using WHERE clause, before aggregations take place:
Select Column name, SUM(column name)
from table name
Where column name= condition
group by column name (By which we want to filter our result)
Filtering groups using HAVING clause, after all aggregations take place:
Select Column name, SUM(column name)
from table name
group by column name (By which we want to filter our result)
Having column name= condition
From a
performance standpoint, you cannot say that one method is less efficient
than the other. SQL server optimizer analyzes each statement and selects
an efficient way of executing it. As a best practice, use the syntax
that clearly describes the desired result. Try to eliminate rows that you wouldn't need, as early as possible.
We can use both WHERE and HAVING in a same queries.It seems to be:
Select Column name, SUM(column name)
from table name
Where Column name= condition
group by column name (By which we want to filter our result)
Having column name= condition
Difference between WHERE and HAVING clause:
1. WHERE clause
can be used with - Select, Insert, and Update statements, where as
HAVING clause can only be used with the Select statement.
2. WHERE filters rows before aggregation (GROUPING), where as, HAVING filters groups, after the aggregations are performed.
3. Aggregate
functions cannot be used in the WHERE clause, unless it is in a sub
query contained in a HAVING clause, whereas, aggregate functions can be used in Having clause.
Comments
Post a Comment