I am trying to merge the data from two tables into one result but without duplicating id’s in the CourseID with the user’s completions taking precedence in the results.
User Course Completion Table
Col Name | Default | PK?
===================================
UserID Y
CourseID Y
SystemComplete NULL N
UserComplete NULL N
UserID, CourseID, SystemComplete, UserComplete
1, 1, NULL, 12/06/2012
1, 2, NULL, 12/06/2012
1, 3, 10/06/2012, 12/06/2012
1, 4, NULL, NULL
1, 5, 10/06/2012, NULL
2, 1, NULL, 12/06/2012
Course to Group table
Col Name | Default | PK?
===================================
CourseID Y
GroupID Y
CourseID, GroupID
1, 1
2, 1
3, 1
4, 1
12, 1
5, 2
6, 2
Expected results
I want to find all of the course completions for a user and supplement that list with the uncompleted items. For example, if I want the list for Group 1 and User 1, I would get
CourseID, SystemComplete, UserComplete
======================================
1, NULL, 12/06/2012
2, NULL, 12/06/2012
3, 10/06/2012, 12/06/2012
4, NULL, NULL
12, NULL, NULL --not in completion record
What I’ve tried
I have tried several queries but I can’t seem to figure this out. The one below was something I found in several questions.
SELECT
COALESCE(uc.CourseID, cg.CourseID) as CourseID
FROM
CoursesToGroup as cg
FULL JOIN UserCompletion as uc ON
uc.CourseID = cg.CourseId
WHERE
uc.UserID = 1 AND
cg.GroupID = 1
…but this only returns a one row result
The closest I have gotten is UNIONing two queries but then I can’t figure out how to get the UserComplete and SystemComplete data into the query
SELECT CourseID
FROM UserCompletion
WHERE
EmployeeID = 1
UNION
SELECT CourseID
FROM CoursesToGroup
WHERE
LearningPathID = 1
This one will return the proper results for the CourseID but, as I stated previously, I can’t figure out how to drop the completion data in there and still remove duplicate CourseId.
What am I missing here?
1 Answer