我有一个包含几列的表。除了最后一列不同之外,有多个包含相同信息的记录。我需要将最后一列合并为其他列。最多只能有3个其他列(课程,课程2,课程3)。以下是我的表格布局。谢谢你的帮助。
Columns
=============
EmployeeNumber
Email
LastName
FirstName
Address1
City
State
Zip
Phone
Certified
School
EmployeeType
BirthDate
Course
StaffNumber
让我尝试一个比我的桌子小的例子...
StaffID FName LName Course
=========================================
1111 John Smith History
1111 John Smith AP History
1111 John Smith Economics
2222 Jane Smith Science
2222 Jane Smith Chemistry
2222 Jane Smith Geology
我需要它来阅读...
StaffID FN LN Course1 Course2 Course3
=======================================================
1111 John Smith History AP History Economics
2222 Jane Smith Science Chemistry Geology
唯一需要包含不同数据的列就是Course。否则,将需要将具有相同数据的几行合并为一个行。
答案 0 :(得分:1)
SELECT *
FROM
(
SELECT
EmployeeNumber,
Email, LastName, FirstName,
Address1, City, State,
Zip, Phone,
Certified,
School,
EmployeeType,
BirthDate,
StaffNumber,
Course as CourseName,
CONCAT('Course', row_number() over (partition by EmployeeNumber order by Course)) AS Col
FROM employee_courses
) src
PIVOT
(
MAX(CourseName)
FOR Col IN ([Course1],[Course2],[Course3])
) pvt