如何压缩此Sql查询的一部分?这需要PIVOT吗?

时间:2016-02-26 02:18:12

标签: sql sql-server tsql

我正在努力压扁我的部分SQL查询。我不确定是否需要PIVOT,或者应使用OVER对子查询进行此操作。

现在,我无法使用我的真实表名,因此我创建了一个代表我们真实系统的非常懊悔的例子。它看起来像是家庭作业,但事实并非如此。

这是复制品(*注意:我试图让它成为一个SqlFiddle,但它还没有工作):

-- Some fake courses/subjects.
DECLARE @Courses TABLE (
    CourseId INTEGER IDENTITY NOT NULL,
    Name VARCHAR(100) NOT NULL)

INSERT INTO @Courses VALUES ('CS100')
INSERT INTO @Courses VALUES ('PY300')
INSERT INTO @Courses VALUES ('AG201')

-- Some teachers that teach the subject/course.
-- Notice there is no ORDER column, so the first teacher is considered
-- The main teacher. the 2nd result is the backup teacher.
-- First teacher = ORDER BY TeacherId ASC (per course)
DECLARE @Teachers TABLE (
    TeacherId INTEGER IDENTITY NOT NULL,
    CourseId INTEGER NOT NULL,
    Name VARCHAR(100)
)

INSERT INTO @Teachers VALUES (1, 'Jane')
INSERT INTO @Teachers VALUES (1, 'John')
INSERT INTO @Teachers VALUES (2, 'Bill')
INSERT INTO @Teachers VALUES (2, 'Anne')
INSERT INTO @Teachers VALUES (3, 'R2D2')

/*
-- Expected output:

CourseId | Cource Name | Primary Teacher | Backup Teacher
----------------------------------------------------------
1        | CS100       | Jane            | John
2        | PY300       | Bill            | Anne
3        | AG201       | R2D2            | <NULL>
*/

有人可以提供一些建议吗?

最后,请不要提出架构建议,比如老师可以在自己的桌子上,然后有CoursesTeachers的加入/链接表(因为同一位老师可以教一个以上的课,对吗?)。

1 个答案:

答案 0 :(得分:1)

您可以尝试此查询:

;with cte as(
select *, row_number() over(partition by CourseId order by TeacherId ASC) as rn
  from @Teachers)

select c.CourseId
     , c.Name as [Cource Name]
     , t1.Name as [Primary Teacher]
     , t2.Name as [Backup Teacher]
  from @Courses c 
      left outer join cte t1 on c.CourseId = t1.CourseId and t1.rn = 1
      left outer join cte t2 on c.CourseId = t2.CourseId and t2.rn = 2