【发布时间】:2013-03-27 16:39:30
【问题描述】:
我正在研究两个系统之间的集成。在我的课程系统中,有一个对应该是工作人员的讲师的引用。问题是 Courses 系统允许在本地创建讲师记录(我已经有一份工作从我们的 Staff 系统馈送到 Courses 系统)。
一门课程可以有不止一位讲师,出于商业原因,有时会创建一个本地讲师记录作为占位符。我需要将所有“真正的”讲师连接成一个字符串,但如果为课程设置的任何讲师不是“真正的”讲师,那么我需要输出一个空字符串。也有可能创建课程时没有分配任何讲师。
课程系统
Courses instructorID InstructorName InstructorOrder
-----------------------------------------------------
ach01 1 Smith 1
ach01 2 Brown 2
phy01 3 James 1
sci01 1 Smith 1
sci01 4 Doe 2
acc01 NULL NULL NULL
员工制度
ID LastName
--------------
1 Smith
2 Brown
3 James
输出
Course Instructors
-------------------------
arc01 'Smith, Brown'
phy01 'James'
sci01 ''
acc01 ''
这是我想出的 SQL,但我想知道是否有更好的方法来获得相同的结果
select courseID,
isnull(case max(case when x.rn = 1 then isnull(lastname, '-|-') else '' end) when '-|-' then NULL else max(case when x.rn = 1 then lastname else '' end) end +
case max(case when x.rn = 2 then isnull(lastname, '-|-') else '' end) when '-|-' then NULL else max(case when x.rn = 2 then ', ' + lastname else '' end) end +
case max(case when x.rn = 3 then isnull(lastname, '-|-') else '' end) when '-|-' then NULL else max(case when x.rn = 3 then ', ' + lastname else '' end) end +
case max(case when x.rn = 4 then isnull(lastname, '-|-') else '' end) when '-|-' then NULL else max(case when x.rn = 4 then ', ' + lastname else '' end) end
, '') Instructors
from (select courseID, s.lastname,
ROW_NUMBER() over(partition by courseID order by InstructorOrder) rn
from Courses c left join
Active_Staff s on c.instructorID = s.ID
) x
group by courseID
【问题讨论】:
-
看看here。
-
谢谢,哈宝。排序顺序不是问题。这在 SQL2005 中通过使用 Row_Number() OVER() 函数来处理。我想知道是否有更好的方法来提交所有 CASE 声明,以确保所有讲师都在教职员工系统中。
-
一门课程不会有超过四位讲师吗?
-
四个是我们允许的最大值。系统中不会有更多。
标签: sql sql-server database sql-server-2005 query-optimization