由于您有动态列,因此您将需要使用动态 SQL 来生成您想要的结果。此查询将生成第二个表中的列列表并将它们 PIVOT 然后连接到SchoolStudent
以获取其他列:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(DynamicColumnName)
from StudentDetails
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = '
select s.studentid,
s.firstname,
s.address,
d.*
from SchoolStudent s
inner join
(
SELECT studentId,' + @cols + '
from
(
select studentId, dynamiccolumnname,
dynamiccolumnvalue
from StudentDetails
) x
pivot
(
max(dynamiccolumnvalue)
for dynamiccolumnname in (' + @cols + ')
) p
) d
on s.StudentId = d.StudentId'
execute(@query);
请参阅SQL Fiddle with Demo。此查询给出结果:
| STUDENTID | FIRSTNAME | ADDRESS | FACEBOOK PROFILE NAME | MOTHER EMAIL | MOTHER NAME | MOTHER OCCUPATION | MOTHER SALARY | VEHICLE REG NO |
-----------------------------------------------------------------------------------------------------------------------------------------------
| 4 | admin | efewfwfew | ross | ram@ram.com | ram@ram.com | ram@ram.com | ram@ram.com | UP 14 as |