我有以下3个表格。
员工:
Name, LastName, SSN
课程实例:
Course, Year, Period
出席者:
Course, SSN, Year, Period, Hours
我正在尝试创建一个存储过程,该存储过程返回一个表,该表在给定年份的前4个过程实例中具有矩阵(作为过程的参数)。
返回的矩阵需要看起来像这样:
Name | LastName | Course | Course | Course | Course
四个不同的Course
是特定年份的前四个课程,所以我现在得到的是找到这些课程的代码:
DECLARE myCursor CURSOR FOR
SELECT top 4 Course
FROM Course Instance
WHERE Year = @year
ORDER by Period
矩阵的其余部分应该只是以某种方式从上面的表中获取值,基本上每个参加过任何课程的工作人员都应该在矩阵中提供正确的信息。在每个Course
列下,我想要参加工作人员的小时数。
示例表
员工:
Name | LastName | SSN
Steve Lastname 234
Pete Steven 132
课程实例:
Course | Year | Period
DVA123 2013 1
DVA222 2014 2
出席者:
Course | SSN | Year | Period | Hours
DVA123 234 2013 1 200
DVA222 132 2014 2 50
预期的输出:
Name | LastName | DVA123 | DVA222 | nothing | nothing
Pete Steven 200
Steve Lastname 50
答案 0 :(得分:2)
我不确定CourseInstance究竟如何链接到参加者,但您可以使用PIVOT和ROW_NUMBER来实现此目的:
WITH Data AS
( SELECT s.Name,
s.LastName,
s.SSN,
ci.Course,
CourseNum = ROW_NUMBER() OVER(PARTITION BY s.SSN ORDER BY ci.Period)
FROM CourseInstance ci
INNER JOIN AttendedBy a
ON a.Course = ci.Course
AND a.Year = ci.Year
AND a.Period = ci.Period
INNER JOIN Staff s
ON s.SSN = a.SSN
WHERE ci.Year = @year
)
SELECT pvt.Name,
pvt.LastName,
Course1 = pvt.[1],
Course2 = pvt.[2],
Course3 = pvt.[3],
Course4 = pvt.[4]
FROM DATA
PIVOT
( MAX(Course)
FOR CourseNum IN ([1], [2], [3], [4])
) pvt;
它使用了MAX(Course)
,但这并不是真正相关,因为CourseNum
对于每个SSN
来说都是唯一的,无论如何你只选择最多的一行。您可以轻松使用MIN
。
我不提倡这种方法,但是,如果您选择动态SQL方法而不是在表示层中执行此操作,它将帮助您入门:
DECLARE @Courses NVARCHAR(MAX) = STUFF((SELECT TOP 4 ',' + QUOTENAME(course)
FROM ( SELECT course, Period, SortOrder = 0
FROM CourseInstance
WHERE Year = @Year
UNION ALL
-- THIS IS REQUIRED TO FILL GAPS WHERE THERE AREN'T ENOUGH COURSES
SELECT TOP 4
'Nothing' + CAST(ROW_NUMBER() OVER(ORDER BY object_id) AS CHAR(1)),
0,
1
FROM sys.all_objects
) t
ORDER BY SortOrder, Period, course
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE @SQL NVARCHAR(MAX) =
' SELECT Name, LastName, ' + @Courses + '
FROM ( SELECT s.Name, s.LastName, s.SSN, ci.Course, a.Hours
FROM AttendedBy a
INNER JOIN Staff s
ON s.SSN = a.SSN
INNER JOIN CourseInstance ci
ON a.Course = ci.Course
AND a.Year = ci.Year
AND a.Period = ci.Period
) d
PIVOT
( SUM(Hours)
FOR Course IN (' + @Courses + ')
) pvt;';
EXECUTE SP_EXECUTESQL @SQL;