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
English 3 Science 4
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.