What is the Query?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mzahid
    New Member
    • Dec 2009
    • 3

    What is the Query?

    I have 3 tables student(s_id,s_ name),course(c_ id,c_name) and student_course( s_id(FK),c_id(F K)).
    I would Like to select those students Name who have enrolled more then and equal to 3 courses.
    What is the Query?
  • debasisdas
    Recognized Expert Expert
    • Dec 2006
    • 8119

    #2
    That seems to be a home work / assignment.

    Kindly post the code that you have tried / working on.

    Comment

    • nbiswas
      New Member
      • May 2009
      • 149

      #3
      Answer to What is the query?

      Try this

      First let's create some sample data

      Code:
      declare @student table(sid int, sname varchar(50))
      declare @course table(cid int, cname varchar(50))
      declare @student_course table(sid int, cid int)
      
      insert into @student 
      	select 1,'student1' union all select 2,'student2' union all
      	select 3,'student3' union all select 4,'student4' union all
      	select 5,'student5' union all select 6,'student6'
      insert into @course 
      	select 101,'course1' union all select 202, 'course2' union all
      	select 303,'course3' union all select 404, 'course4' union all
      	select 505,'course5' union all select 606, 'course6' 
      insert into @student_course
      	select 1,101 union all select 1,202 union all select 1,303 union all
      	select 1,404 union all select 1,505 union all select 1,606 union all
      	select 2,101 union all select 2,505 union all select 2,606 union all
      	select 3,303 union all select 3,202 union all select 4,303 union all
      	select 4,404 union all select 4,202 union all select 5,101 union all 
      	select 6,101 union all select 6,202
      Query 1:

      Code:
      select s.sid,s.sname from @student s
      inner join
      (	
      select sid,COUNT(cid) Courses from @student_course 
      group by sid
      having (COUNT(cid)>=3))X
      on X.sid = s.sid
      Query 2:
      Code:
      select sid,sname from @student where sid in(
      select sid from @student_course 
      group by sid
      having (COUNT(cid)>=3))
      The output(in both the cases)

      Code:
      sid	sname
      1	student1
      2	student2
      4	student4
      Hope this helps

      Comment

      • mzahid
        New Member
        • Dec 2009
        • 3

        #4
        What is the Query?

        Thank you very much sir.....

        Comment

        Working...