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 |
atulkukreja
Starting Member
13 Posts |
Posted - 2012-01-09 : 20:17:33
|
Using SQL Server 2005 Express.Table Definitions:CREATE TABLE [dbo].[subjects] ( [subject] varchar(50) NOT NULL,) ON [PRIMARY]goINSERT INTO [subjects] ([subject])VALUES('Math')INSERT INTO [subjects] ([subject])VALUES('English')INSERT INTO [subjects] ([subject])VALUES('Biology')INSERT INTO [subjects] ([subject])VALUES('Physics')CREATE TABLE [dbo].[studentSubjects] ( [student] varchar(50) NOT NULL, [subject] varchar (50) NOT NULL ) ON [PRIMARY]goINSERT INTO [studentSubjects] ([student],[subject])VALUES('Jim','Math')INSERT INTO [studentSubjects] ([student],[subject])VALUES('Kim','Math')INSERT INTO [studentSubjects] ([student],[subject])VALUES('Kim','Biology')I'd like to list all students and all subjects, with a 'Y' if the subject is selected or 'N' if the subject is not selected:Student Subject Selected?--------------------------Jim Math YJim English NJim Biology NJim Physics NKim Math YKim English NKim Biology YKim Physics NI have tried a cross join (select S.studentName, T.subject, case when S.subject = T.subject then 'Y' else 'N' end from studentSubjects S cross join subjects T order by 1,2) but it yields incorrect results and I cannot find the SQL to do this, any help is greatly appreciated.scptech |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-01-10 : 04:19:55
|
[code]SELECT m.Student,m.subject,CASE WHEN n.subject IS NOT NULL THEN 'Y' ELSE 'N' END AS [Selected]FROM(SELECT s.Student,sb.subjectFROM (SELECT DISTINCT Student FROM studentSubjects) sCROSS JOIN subjects sb)mLEFT JOIN studentSubjects nON n.Student = m.StudentAND n.subject = m.subject[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
atulkukreja
Starting Member
13 Posts |
Posted - 2012-01-10 : 08:03:06
|
Thanks for the quick response visakh16, that works perfectly. |
 |
|
|
|
|
|
|