Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
scptech
Starting Member
8 Posts |
Posted - 2008-05-16 : 11:44:27
|
I have 3 tables, students (studentId, studentName), classes (classId, className) and studentclass (studentId, classId, sessionId)Want to display all studentnames, classnames and sessionIds, regardless of whether the student is enrolled in a specific class or not.So the result set should show all students and all classes:studentname classname sessionId----------- --------- ---------john english 2john math <null>jane english <null>jane math 3Please help in how to write such SQL?Thanks in advance |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-05-16 : 11:50:06
|
Can i see what you tried till now? |
 |
|
scptech
Starting Member
8 Posts |
Posted - 2008-05-16 : 11:54:58
|
I have nothing to show you, since it is the first time I am trying something like this..... |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-05-16 : 12:30:28
|
SELECT s.studentName,c.className,sc.sessionIdFROM students sLEFT JOIN studentclass scON sc.studentId = s.studentIdLEFT JOIN classes cON c.classId=sc.classIdMake sure you read about joins on books online to learn how they works. |
 |
|
scptech
Starting Member
8 Posts |
Posted - 2008-05-16 : 12:43:38
|
Thank you.Your SQL is not Ok, it will not give all the rows in both students and classes. If you have 2 rows in students and 2 in classes, and 0 in studentclasses, the result set should show 4 rows with nulls in the last column. |
 |
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2008-05-16 : 12:52:25
|
[code]DECLARE @students TABLE (studentId INT, studentName VARCHAR(20))DECLARE @classes TABLE (classId INT, className VARCHAR(20)) DECLARE @studentclass TABLE (studentId INT, classId INT, sessionId INT)INSERT @StudentsSELECT 1, 'Frank'UNION ALL SELECT 2, 'Billy'INSERT @ClassesSELECT 1, 'Math'UNION ALL SELECT 2, 'English'INSERT @studentclassSELECT 1, 2, 100UNION ALL SELECT 2, 1, 999SELECT s.studentName,c.className,sc.sessionIdFROM @students sCROSS JOIN @classes cLEFT JOIN @studentclass scON sc.studentId = s.studentIdAND sc.classId = c.classId[/code] |
 |
|
scptech
Starting Member
8 Posts |
Posted - 2008-05-16 : 15:07:13
|
thanks a lot. |
 |
|
|
|
|
|
|