在sql server 2008中使用外部/左侧连接进行分组

时间:2013-02-05 06:15:25

标签: sql sql-server-2008 join group-by

我在1表中有数据

UserID CourseID TestID   Result
1         1       1        P
1         1       2        P
2         1       1        F
2         1       2        F

这显示2个用户(UserID = 1和2)在CourseID = 1中采用了测试(TestID = 1和2)

现在,CourseID总共有3个测试(比如TestID = 1,2,7)为

CourseID TestID
1          1
1          2
1          7

这意味着用户没有采取Test(TestID = 7)显示现在我想显示数据如下

UserID CourseID TestID   Result
1         1       1        P
1         1       2        P
1         1       7        null
2         1       1        F
2         1       2        F
2         1       7        null

我一直尝试使用Group by左/右外连接,但无法获得所需的结果。如何实现?

2 个答案:

答案 0 :(得分:2)

SQL Fiddle

MS SQL Server 2008架构设置

create table Result
(
  UserID int,
  CourseID int,
  TestID int,
  Result char(1)
)
insert into Result values
(1,         1,       1,        'P'),
(1,         1,       2,        'P'),
(2,         1,       1,        'F'),
(2,         1,       2,        'F')

create table Course
(
  CourseID int,
  TestID int
)

insert into Course values
(1, 1),
(1, 2),
(1, 7)

查询1

select U.UserID,
       C.CourseID,
       C.TestID,
       R.Result
from (
     select distinct UserID
     from Result
     ) as U
  cross apply Course as  C
  left outer join Result as R
    on R.CourseID = C.CourseID and
       R.TestID = C.TestID and
       R.UserID = U.UserID

<强> Results

| USERID | COURSEID | TESTID | RESULT |
---------------------------------------
|      1 |        1 |      1 |      P |
|      1 |        1 |      2 |      P |
|      1 |        1 |      7 | (null) |
|      2 |        1 |      1 |      F |
|      2 |        1 |      2 |      F |
|      2 |        1 |      7 | (null) |

注意:如果您有一个表Users,则可以替换派生表

 (
 select distinct UserID
 from Result
 ) as U

代替Users as U

答案 1 :(得分:0)

SELECT uct.UserId, ct.CourseID, ct.TestID, uct.Result
FROM CourseTest ct
LEFT JOIN UserCourseTest uct ON uct.CourseID=ct.CourseID AND uct.TestID=ct.TestID