Wednesday 29 January 2014

SSRS SQL Query: Nested join relationship handling

Scenario:
Every time you use a join query you have to use the keyword ON before the matched columns. What happens if you need say for example 6 join statement. In this case you can create a separate query for the matched columns then use that in the following join query to compare the matched columns.

DECLARE     @Y1RefDate1 Date, @Y1RefDate2 Date ,@CollegeYear1 Int, @CollegeYear2 int, @CollegeYear3 int
  
SET         @Y1RefDate1 = '12-OCT-2013'
SET         @Y1RefDate2 = '01-JAN-2014'
SET         @CollegeYear1 = 2013
SET         @CollegeYear2 = 2012
SET         @CollegeYear3 = 2011

SELECT                        CourseList.Course
                              ,CR1.Total                    AS Y1Start
                              ,CR2.Total                    AS Y1End
                              ,CR3.Total                    AS Y2Start
                              ,CR4.Total                    AS Y2End
                              ,CR5.Total                    AS Y3Start
                              ,CR6.Total                    AS Y3End 
FROM 
--Full list(List of course for that will be matched column with other join query)
(SELECT     DISTINCT    CourseCode  + ' ' + Cohort    AS Course  
FROM                    xvwCourseRetention
WHERE                   CourseYear = @CollegeYear1
      OR                      CourseYear = @CollegeYear2
      OR                      CourseYear = @CollegeYear3
GROUP BY                CourseCode, Cohort)                                         AS CourseList

--Add current year start figure
LEFT JOIN 
(SELECT     DISTINCT    CourseCode  + ' ' + Cohort    AS Course
                              ,COUNT(StudentID)             AS Total   
FROM                    xvwCourseRetention
WHERE                   CourseYear = @CollegeYear1
            AND               StartDate<=@Y1RefDate1
            AND               (ActualEndDate>@Y1RefDate1 OR ActualEndDate IS NULL)
GROUP BY                CourseCode, Cohort)                                         AS CR1 

ON                            CR1.Course = CourseList.Course

ORDER BY                1


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home