Q

Why WHERE cannot be used after GROUP BY

Please tell me why "where" can't be used after "group by".

WHERE operates on individual rows, and is used to select which rows will participate in grouping. HAVING operates on groups, and is used to select which groups will be returned. Here's an example:

student	subject	grade
 Bill   English   A
 Bill   French    B
 Bill   History   C
 Bill   Math      D
 Bill   Science   A
 Bill   Spelling  C
 Bob    English   A
 Bob    French    B
 Bob    History   D
 Bob    Math      C
 Bob    Science   C
 Bob    Spelling  F
 Fred   English   A
 Fred   French    A
 Fred   History   C
 Fred   Math      C
 Fred   Science   A
 Fred   Spelling  C
 John   English   C
 John   French    D
 John   History   B
 John   Math      F
 John   Science   A
 John   Spelling  C
 Mary   English   C
 Mary   French    C
 Mary   History   F
 Mary   Math      C
 Mary   Science   C
 Mary   Spelling  C
 Tom    English   D
 Tom    French    A
 Tom    History   B
 Tom    Math      C
 Tom    Science   A
 Tom    Spelling  F

In which subjects did at least three students earn an A?

To find the answer, you have to count the number of students who got an A in each subject. In other words, you need to filter on the grade, selecting only those student subjects where the grade was A. Then you have to look at the count for each subject, and return only those subjects which have at least three selected students in them.

select subject, count(*)
  from studentgrades
 where grade = 'A'
group 
    by subject
having count(*) > 2

The answer:

English  3
Science  4

For More Information


This was first published in November 2002

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close