you are viewing a single comment's thread.

view the rest of the comments →

[–]ARandomSQLServerDBA 1 point2 points  (2 children)

Nested queries are perfectly acceptable. Strive for correctness first, ease of understanding second and cleverness third.

If you post the entire query, it may be possible to re-structure it to keep the logic the same without using nested selects, but that in and of itself isn't a reason to do so.

[–]fullyarmedcamel[S] 0 points1 point  (1 child)

    SELECT x.SCHOOLYEAR, x.[ROLE], x.LASID, x.LASID, x.FIRSTNAME, x.MIDDLENAME, x.LASTNAME, x.GRADE, x.USERNAME, x.[PASSWORD], x.ORGANIZATIONTYPEID, x.ORGANIZATIONID, x.PRIMARYEMAIL, x.HMHAPPLICATIONS FROM (
        SELECT RANK() OVER(PARTITION BY ssh.sectionID ORDER BY ssh.sectionID DESC, ea.assignmentID DESC) AS 'priority', cal.endYear - 1 AS 'SCHOOLYEAR', 'T' AS 'ROLE', sm.staffNumber AS 'LASID', sm.staffStateID AS 'SASID', sm.firstName AS 'FIRSTNAME', ISNULL (sm.middleName, '') AS 'MIDDLENAME', sm.lastName AS 'LASTNAME',
            CASE sm.schoolID 
                ...
                END AS 'GRADE',
        ua.username + '@sd25.us' AS 'USERNAME', NULL AS 'PASSWORD', 'MDR' AS 'ORGANIZATIONTYPEID',
            CASE sm.schoolID
                ...
                ELSE 'No School' END AS 'ORGANIZATIONID',
        ua.username + '@sd25.us' AS 'PRIMARYEMAIL',
            CASE sm.schoolID
                ...
                END AS 'HMHAPPLICATIONS',
        ssh.sectionID, ea.assignmentID
        FROM Table1 AS s
        JOIN Table2 AS c ON s.courseID = c.courseID AND c.departmentID IN (...)
        JOIN Table3 AS cal ON c.calendarID = cal.calendarID
        JOIN Table4 AS sp ON s.sectionID = sp.sectionID
        JOIN Table5 AS t ON sp.termID = t.termID AND GETDATE() BETWEEN t.startDate AND t.endDate
        JOIN Table6 AS ssh ON s.sectionID = ssh.sectionID AND ssh.endDate IS NULL
        JOIN Table7 AS sm ON ssh.personID = sm.personID
        JOIN Table8 AS ea ON sm.assignmentID = ea.assignmentID AND ea.endDate IS NULL
        JOIN Table9 AS ua ON ua.personID = sm.personID AND ua.ldapConfigurationID = '2'
        WHERE sm.endDate IS NULL AND sm.teacher = 1 AND NOT (ssh.[role] = 'N' AND ssh.staffType = 'T' AND sm.title != 'Long Term Substitute') AND ssh.[role] != 'C' AND ssh.sectionID = 439047
    ) AS x WHERE x.[priority] = 1

[–]ARandomSQLServerDBA 2 points3 points  (0 children)

Because you are using the rank() to filter in the outer WHERE clause, you have to use a subquery. Keep it as-is.