• a_ud (5/2/2013)


    <snipped>

    The weeks table stores values 1..5. The PAscores table stores the scores for different volunteers. I'd like to have the missing entries in tblPAscores; if volunteer John is missing week 4's score, the query would produce that, asa said above.

    Am I missing something? Thanks

    You may find this easier if you have a People table holding the names of all people.

    Once you have a Weeks table, a People table, and a Scores table, express the result you want in plain language:

    "Person and Week where the Person does not have a Score for that Week."

    That helps make it clear that you want to start with People and Weeks and eliminate PersonID/Week combinations for which Scores exist.

    Two possibilities:

    SELECT p.PersonID, w.WeekNbr

    FROM People p

    CROSS APPLY Weeks w

    EXCEPT

    SELECT s.PersonID, s.WeekNbr

    FROM Scores s

    SELECT p.PersonID, w.WeekNbr

    FROM People p

    CROSS APPLY Weeks w

    WHERE NOT EXISTS (SELECT 1 FROM Scores s WHERE s.PersonID = p.PersonID AND s.WeekNbr = w.WeekNbr)

    Querying for values that do NOT exist in a table is very costly without appropriate indexes. If you have a significant amount of data, you'll probably want to look into indexing your tblPAScores table on VolunteerID and NoWeek.

    BTW, you will find that using the prefix "tbl" on your table names, or "tibbling", as some call it, will provoke visceral negative reactions from some members of the SQL Server community. Including schema metadata ("tbl" in the table name identifies the object as a table) in object names violates ISO standards, which riles up some folks. Also, using "No" to stand for "Number" in object names can be confusing (does it mean "number" or "no"?) - I much prefer using "Number" or "Nbr". I use "Number" whenever feasible because it's unambiguous and easily human-readable. The 128-character limit on identifiers in SQL Server is very generous, so abbreviations are less necessary than they once were.

    Jason Wolfkill