在这里,我试图分三步展示你的答案。
CREATE TABLE [SeekerCources](
[SeekerID] [nvarchar](50) NULL,
[CourceName] [nvarchar](50) NULL,
[Duration] [nvarchar](50) NULL
)
CREATE TABLE [SeekerInfo](
[SeekerID] [nvarchar](50) NULL,
[SeekerName] [nvarchar](50) NULL,
[SeekerSex] [nvarchar](50) NULL,
[SeekerMobile] [nvarchar](50) NULL
)
INSERT [SeekerCources] ([SeekerID], [CourceName], [Duration]) VALUES (N'12121', N'MCSA', N'1 year')
INSERT [SeekerCources] ([SeekerID], [CourceName], [Duration]) VALUES (N'12121', N'MCPD', N'6 months')
INSERT [SeekerCources] ([SeekerID], [CourceName], [Duration]) VALUES (N'13223', N'CCNA', N'1 year')
INSERT [SeekerCources] ([SeekerID], [CourceName], [Duration]) VALUES (N'13223', N'CCNP', N'1 year')
INSERT [SeekerCources] ([SeekerID], [CourceName], [Duration]) VALUES (N'13223', N'MCTS', N'4 months')
INSERT [SeekerInfo] ([SeekerID], [SeekerName], [SeekerSex], [SeekerMobile]) VALUES (N'12121', N'mmmm', N'Male', N'067676767')
INSERT [SeekerInfo] ([SeekerID], [SeekerName], [SeekerSex], [SeekerMobile]) VALUES (N'13223', N'ssss', N'Female', N'078876767')
步骤1
Select SeekerID, CourceName,
'Course' + CAST(ROW_NUMBER() over (partition by SeekerID order by CourceName) as varchar(10)) as CourseSquence
from SeekerCources
第 1 步的结果应如下所示。
演示:链接
第2步
Select SeekerID, Course1, Course2, Course3
from
(
select SeekerID, CourceName,
'Course' + CAST(ROW_NUMBER() over (partition by SeekerID order by CourceName) as varchar(10)) as CourseSquence
from SeekerCources
) Temp
Pivot
(
Max(CourceName)
For CourseSquence in (Course1, Course2, Course3)
) PIV
第 2 步的结果应如下所示。
演示:链接
第 3 步
Select SeekerInfo.*, PIV.SeekerID, Course1, Course2, Course3
from
(
select SeekerID, CourceName,
'Course' + CAST(ROW_NUMBER() over (partition by SeekerID order by CourceName) as varchar(10)) as CourseSquence
from SeekerCources
) Temp
Pivot
(
Max(CourceName)
For CourseSquence in (Course1, Course2, Course3)
) PIV
inner join SeekerInfo on SeekerInfo.SeekerID = PIV.SeekerID
第 3 步的结果应如下所示。
演示:链接
解说
视频 1:SQL Server 中的 Pivot - https://youtu.be/h3BtudZehuo
视频 2:将行转换为列 - https://youtu.be/C0mQqDnF7wQ