Question

Consider the following database setup:

CREATE TABLE ClassStud (

uname varchar(10) NOT NULL,

classcode varchar(7) NOT NULL,

grnr varchar(8),

sem varchar(6) NOT NULL
);

INSERT INTO ClassStud(uname,classcode, grnr,sem) VALUES ('oscali', 'inf1000', 'group1', '2013-2');
INSERT INTO ClassStud(uname,classcode, grnr,sem) VALUES ('oscali', 'inf1300', 'group2', '2013-2');
INSERT INTO ClassStud(uname,classcode, grnr,sem) VALUES ('axelboi', 'inf1100', 'group3', '2013-2');
INSERT INTO ClassStud(uname,classcode, grnr,sem) VALUES ('fredrbhe', 'inf2100', 'group2', '2013-2');
INSERT INTO ClassStud(uname,classcode, grnr,sem) VALUES ('vetleoj', 'inf2200', 'group6', 2013-2');

With uname being username, grnr being groupnumber and sem being the semester.

What I'm trying to figure out is how to find the the group with the smallest number of members (no matter the course/class). I've been stuck with this problem for a few hours now and even searching the net I haven't found much to help or guide me in the right direction.

I tried it this way

SELECT classcode, grnr, COUNT(uname) AS students_in_group
FROM ClassStud
WHERE grnr is NOT NULL
AND sem LIKE '2013-2'
GROUP BY classcode, grnr
HAVING MIN(students_in_group);

but I get an error saying students_in_group does not exist. I have also tried with a subquery and having MIN() in SELECT with no luck.

SELECT classcode, grnr, MIN(students)
FROM (
SELECT count(uname) AS students FROM ClassStud) AS s, ClassStud
WHERE grnr IS NOT null
AND sem LIKE '2013-2'
GROUP BY classcode, grnr;

Problem here being that it's a VARCHAR I need to be counting and not a Integer.

EDIT: Forgot to add that the query/search should only display the smallest group. That is the real problem. I have also tried creating a view with all the groups and then asking for the smallest one, but for some reason it ends up printing the whole view.

Was it helpful?

Solution

Maybe try this:

SELECT classcode, grnr, COUNT(uname) AS students_in_group
FROM ClassStud
WHERE grnr is NOT NULL
AND sem LIKE '2013-2'
GROUP BY classcode, grnr
Order by count(uname)
LIMIT 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top