0

我正在尝试将两个表中的数据合并到一个结果中,但不复制 id,CourseID而用户的完成优先于结果。

用户课程完成表

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

预期成绩

我想查找用户的所有课程完成情况,并用未完成的项目补充该列表。例如,如果我想要 Group1和 User的列表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

我试过的

我已经尝试了几个查询,但我似乎无法弄清楚这一点。下面的一个是我在几个 问题中发现的。

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两个查询,但是我不知道如何将UserCompleteandSystemComplete数据放入查询中

SELECT CourseID
FROM UserCompletion
WHERE
  EmployeeID = 1

UNION

SELECT CourseID
FROM CoursesToGroup
WHERE
  LearningPathID = 1

这将返回正确的结果,CourseID但是,正如我之前所说,我无法弄清楚如何将完成数据放入其中并仍然删除重复CourseId

我在这里想念什么?

4

1 回答 1

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)
于 2012-06-27T20:28:04.313 回答