DECLARE @CURRENTSCHOOL TABLE (STUDENT VARCHAR(8), COURSE VARCHAR(8), SCHOOL VARCHAR(2))
INSERT INTO @CURRENTSCHOOL VALUES ('10000000','MCR1010','11')
INSERT INTO @CURRENTSCHOOL VALUES ('12000000','MCR6080','11')
INSERT INTO @CURRENTSCHOOL VALUES ('13000000','MCR6090','15')
DECLARE @OTHERSCHOOLS TABLE (STUDENT VARCHAR(8), COURSE VARCHAR(8), SCHOOL VARCHAR(2))
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1010','11')
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1011','14')
INSERT INTO @OTHERSCHOOLS VALUES ('10000000','MCR1012','15')
INSERT INTO @OTHERSCHOOLS VALUES ('12000000','MCR6080','19')
INSERT INTO @OTHERSCHOOLS VALUES ('13000000','MCR6090','15')
For the above sample data. Two tables. Currentschool and Otherschools.
Currentschool is the current course that a student is on including the schoolcode,
and is the main table.
OtherSchools is potentially other courses that a student can go on, in differing schools.
I need to compare the currentschool table against the otherschools table matched using the student id number, and for every different schoolcode in otherschools, it needs to return a count.
eg:
Student: OtherSchoolCount:
10000000 2 (because of 2 different school codes than than the current school)
12000000 1 (because of 1 different school code than than the current school)
13000000 blank (because not a different school code)
Is this possible?
Many thanks
M.
outputs
If Null is really preferred over Zero then you can do this (or use the equivalent CTE)
Which outputs
Update: NullIF could be put to use as alternative to the Case statement see What applications are there for NULLIF()?