blog post

HAVING filters records that work on summarized GROUP BY results.
HAVING applies to summarized group records, whereas WHERE applies to individual records.
Only the groups that meet the HAVING criteria will be returned.
HAVING requires that a GROUP BY clause is present.
WHERE and HAVING can be in the same query.

SQL GROUP BY Examples

Problem: List the number of customers in each country. Only include countries with more than 10 customers.
SELECT COUNT(Id), Country 
  FROM Customer
 GROUP BY Country
HAVING COUNT(Id) > 10

Problem: List the number of customers in each country, except the USA, sorted high to low.
Only include countries with 9 or more customers.
SELECT COUNT(Id), Country 
  FROM Customer
 WHERE Country <> 'USA'
 GROUP BY Country
HAVING COUNT(Id) >= 9
 ORDER BY COUNT(Id) DESC

Problem: List all customer with average orders between $1000 and $1200.
SELECT AVG(TotalAmount), FirstName, LastName
  FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id
 GROUP BY FirstName, LastName
HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200

  • Share This Story


Pleas give your valuable comments to improve the contents.

about author

Atul kumar shukla


I'm Atul Kumar Shukla, working as a web developer.
Welcome to my Blog. This is my personal blog where i post my own questions and answers , articles about ASP.Net., SQL Server, HTML, CSS, Jquery and many more..

Visit Profile

Leave a comment

Name
E-mail
Url
Message

Get More Stuff
Subscribing to the TheOneblogs newsletter and get intersting stuff and updates to your email inbox.
Your Email

 

Style Switcher

Change Color

×! We use cookies to improve your user experience. More information