| Author |
Topic  |
|
|
Prosercunus
Starting Member
USA
22 Posts |
Posted - 10/11/2012 : 23:04:27
|
Using select statements find the name(s) and sid(s) of the student(s) enrolled in the most classes.
So far I have...
select Student.sid, sname, Major.dname from Student, Major
I now need to find those students that are enrolled in the most classes. I can see all of the classes they are in, just unsure what statement to make it show it only shows the students enrolled in the most amount of classes or (dname).
Here are the two tables.
Major(dname,sid) Student(sid,sname,sex,age,year,qpa) |
|
|
sql-programmers
Posting Yak Master
USA
189 Posts |
Posted - 10/12/2012 : 00:33:01
|
Hi,
Try this,
DECLARE @Major AS TABLE (dname VARCHAR(50),SID INT ) DECLARE @Student AS TABLE (SID INT IDENTITY,sname VARCHAR(50),sex CHAR(1),age INT,[year] INT)
INSERT INTO @Student (sname, sex, age, [year]) VALUES ('A', 'M', 12, 1999) INSERT INTO @Student (sname, sex, age, [year]) VALUES ('B', 'M', 13, 2000) INSERT INTO @Student (sname, sex, age, [year]) VALUES ('C', 'F', 13, 2000) INSERT INTO @Student (sname, sex, age, [year]) VALUES ('D', 'M', 15, 1999) INSERT INTO @Student (sname, sex, age, [year]) VALUES ('E', 'F', 16, 1999)
INSERT INTO @Major ( dname, SID )VALUES ( 'D 1', 1) INSERT INTO @Major ( dname, SID )VALUES ( 'D 2', 1) INSERT INTO @Major ( dname, SID )VALUES ( 'D 3', 1) INSERT INTO @Major ( dname, SID )VALUES ( 'D 1', 2) INSERT INTO @Major ( dname, SID )VALUES ( 'D 2', 2) INSERT INTO @Major ( dname, SID )VALUES ( 'D 1', 3) INSERT INTO @Major ( dname, SID )VALUES ( 'D 2', 4) INSERT INTO @Major ( dname, SID )VALUES ( 'D 3', 5)
SELECT M.SID, COUNT(*) FROM @Student S INNER JOIN @Major M ON s.SID = m.SID GROUP BY M.SID HAVING COUNT(*) > 1
SELECT S.SID, S.sname, M.dname FROM @Student S INNER JOIN ( SELECT M.SID, COUNT(*) AS Cnt FROM @Student S INNER JOIN @Major M ON s.SID = m.SID GROUP BY M.SID HAVING COUNT(*) > 1 ) AS M1 ON m1.SID = s.sid INNER JOIN @Major M ON M1.SID = m.SID
SQL Server Programmers and Consultants http://www.sql-programmers.com/ |
 |
|
|
bandi
Flowing Fount of Yak Knowledge
India
1390 Posts |
Posted - 10/12/2012 : 00:36:48
|
Hi,
Alternate Solution is:
;with cte as (SELECT sid, dname, count(dname) over(Partition by sid) noOfDepts from Major) select S.*, dname, noOfDepts FROM student s JOIN cte m ON s.sid = m.sid WHERE noOfDepts = (SELECT MAX(noOfDepts) FROM cte)
-- Chandu |
 |
|
| |
Topic  |
|
|
|