Difference between Group by and Having Clause
Group By:The GROUP BY clause will gather all of the rows together that contain data in the specified
column(s) and will allow aggregate functions to be performed on the one or more columns.
Aggregate functions are like SUM,COUNT,MIN,MAX and AVG.
Example :
Consider the folowing table of Appriasal
Table Name : Appraisal
Emp_id | Amount |
---|---|
E01 | 2000 |
E02 | 4000 |
E03 | 5000 |
E02 | 6000 |
E01 | 2000 |
Query :
So if you want to get employee record who got total appraisal in one year then your query will be :
Select Emp_id, SUM(Amount)
from Appraisal
Group by Emp_id.
Result :
Emp_id | Amount |
---|---|
E01 | 4000 |
E02 | 10000 |
E03 | 5000 |
Having: The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT statement to filter the records that a GROUP BY returns.
Group functions cannot be used in where.To restrict row by group function having clause is used.
Example :Consider the folowing table of Appriasal
Table Name : Appraisal
Emp_id | Amount |
---|---|
E01 | 2000 |
E02 | 4000 |
E03 | 5000 |
E02 | 6000 |
E01 | 2000 |
Query :
So Now if you want to get employee record who got total appraisal in one year more than 5000 then your query will be :
Select Emp_id, SUM(Amount)
from Appraisal
Group by Emp_id Having SUM(Amount)>5000.
Result :
Emp_id | Amount |
---|---|
E02 | 10000 |
No comments:
Post a Comment