Q

A sample query for students with most classes

Expert Adam Machanic offers a sample query to find the names of the students enrolled in the largest number of classes.

Consider a database with the following tables (the sets of underlined attributes are primary keys):

Student (*sid: integer, *sname: string, *age: integer)

Class (*cname: string, *meets_at: datetime, *day: datetime, *room: string)

Enrolled (*sid: integer, *cname: string)

What query would you write to find the names of the students enrolled in the largest number of classes?

SELECT 
    S.SName,
    COUNT(*) AS EnrolledCount
FROM Student S
JOIN Enrolled E ON S.sid = E.sid
GROUP BY S.SName
ORDER BY COUNT(*) DESC
… But you'll have to decide what "largest number" means and add your own logic to filter the results further based on a threshold number that qualifies. You might employ a HAVING clause for that purpose.
This was last published in January 2006

Dig Deeper on SQL-Transact SQL (T-SQL)

PRO+

Content

Find more PRO+ content and other member only offers, here.

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.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchBusinessAnalytics

SearchDataCenter

SearchDataManagement

SearchAWS

SearchOracle

SearchContentManagement

SearchWindowsServer

Close