我正在尝试将两个表中的数据合并为一个结果,但不会在CourseID
中复制id,而用户的完成优先于结果。
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
Col Name | Default | PK?
===================================
CourseID Y
GroupID Y
CourseID, GroupID
1, 1
2, 1
3, 1
4, 1
12, 1
5, 2
6, 2
我希望找到用户的所有课程完成情况,并使用未完成的项目补充该列表。例如,如果我想要群组1
和用户1
的列表,我会得到
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
我已经尝试了几个查询,但我似乎无法解决这个问题。下面的内容是我在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
...但这只返回一行结果
我得到的最接近的是UNION
两个查询,但后来我无法弄清楚如何将UserComplete
和SystemComplete
数据放入查询中
SELECT CourseID
FROM UserCompletion
WHERE
EmployeeID = 1
UNION
SELECT CourseID
FROM CoursesToGroup
WHERE
LearningPathID = 1
这个会返回CourseID
的正确结果,但正如我之前所述,我无法弄清楚如何删除完成数据并仍然删除重复CourseId
。
我在这里缺少什么?
答案 0 :(得分:2)
SELECT CourseID, SystemComplete, UserComplete
FROM UserCompletion
WHERE
UserId = 1
UNION
SELECT CourseId, null, null
FROM CoursesToGroup
where GroupId = 1
and CourseId NOT IN
(SELECT CourseId From UserCompletion
WHERE UserId = 1)