-1

To have students (student_id, course_id, course_name) who take exactly only one course, using a simple SQL statement with no sub-query and no join at all

student_id  course_id   course_name
---------------------------------------------
1       1000        'CS 101'
2       1000        'CS 101'
1       2000        'CHEM 200'
2       3000        'ENG 211'
3       1000        'CS 101'
4       5000        'Bio 400'

Any one please me on this. Tried many approaches but couldn't get the answer without sub query.

jeff
  • 157
  • 1
  • 2
  • 8

3 Answers3

1

Use group by with having

select student_id,count(course_id) as num 
from students group by student_id
having num =1

or this :-

select student_id
from students group by student_id
having count(course_id) =1
Abhishek Sharma
  • 6,689
  • 1
  • 14
  • 20
1

It is possible to retrieve just the STUDENT_ID for students on just one course:

SQL>  SELECT student_id
  2   FROM students 
  3   GROUP BY student_id
  4   HAVING COUNT(course_id) = 1 
  5   /


STUDENT_ID
----------
         4
         3

Elapsed: 00:00:00.09
SQL> 

But to get additional information, such as the course name, then we need to use a sub-query or join.

APC
  • 144,005
  • 19
  • 170
  • 281
-2

How about using GROUP BY and HAVING COUNT

SELECT student_id, course_name FROM students 
GROUP BY student_id, course_name
HAVING COUNT(course_id) = 1 
japzdivino
  • 1,736
  • 3
  • 17
  • 25