Usage of Having Clause

2012-07-03


We use group by  clause when you want to get result against a field, for example total no. of  medals won by countries against each sports event in an Olympics.



1
Select Country,Sum(Medal) From ScoreTable Group By Country



What if you want to list only the countries which has got total no. of medals exceeding 100.



1
Select Country,Sum(Medal) From ScoreTable Group By Country having Sum(Medal)>100



i.e use having clause when you want to filter against the result which is already grouped. Here you cannot use the where clause since the where clause doesn't work with aggregates – like sum, avg, max, etc.. Instead, what we will need to use is the having clause. The having clause was added to sql just so we could compare aggregates to other values – just how the ‘where’ clause can be used with non-aggregates. 

0 comments: