Domanda

I'm using DATEDIFF and IS NULL to find records missing data for a certain number of days, For example, here I'm trying to find students who haven't taken any classes for 1095 days (3 years), if they're a registered student they can't go more than 3 years without taking any classes. I think I'm doing this right, just making sure. As I'm learning, after the OUTER JOIN all columns return back and you filter columns you do/don't want in the WHERE.

SELECT DISTINCT
    stu.campusID AS [Campus ID],
    camp.name AS [School],
    stu.studentID AS [Student ID],
    stu.lName AS [Last Name],
    stu.fName AS [First Name]

FROM
    students stu
    LEFT OUTER JOIN
    coursesTaken cour
    ON
    cour.campusID = stu.campusID
    AND
    cour.studentID = stu.studentID
    AND
    DATEDIFF(D, cour.dateTaken, GETDATE()) >= 1095
    INNER JOIN
    campusNames camp
    ON
    camp.campusID = stu.campusID

WHERE
    cour.dateTaken IS NULL
È stato utile?

Soluzione

If you're wanting to find students that haven't taken any courses for the last 3 years, there's a couple of things I'd change around:

SELECT
    stu.campusID AS [Campus ID],
    camp.name AS [School],
    stu.studentID AS [Student ID],
    stu.lName AS [Last Name],
    stu.fName AS [First Name]

FROM
    students stu
      INNER JOIN
    campusNames camp
      ON
        camp.campusID = stu.campusID
WHERE
    NOT EXISTS (SELECT * FROM coursesTaken co
           where co.StudentID = stu.StudentID and
           co.DateTaken > DATEADD(year,-3,GETDATE())

Which hopefully reads more cleanly/closely to your spec. (You can change the DATEADD back to using 1095 days if that's the actual requirement, but if it's 3 years then the above is better because it takes leap years into account)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top