Я считаю, что это решит ваши потребности:
STATIC PIVOT
create table #form
(
form_id int,
form_name varchar(50)
)
create table #form_field
(
form_field_id int,
form_id int,
label varchar(50)
)
create table #registration
(
reg_id int,
form_id int,
userid int
)
create table #registration_info
(
reg_id int,
form_field_id int,
field_value varchar(50)
)
insert into #form values(500, 'Custom Form 1')
insert into #form_field values(1, 500, 'Field 1')
insert into #form_field values(2, 500, 'Field 2')
insert into #registration values(23, 500, 45)
insert into #registration values(24, 500, 98)
insert into #registration_info values(23, 1, 'My Name')
insert into #registration_info values(24, 2, 'My City')
select r.reg_id
, IsNull(p.[Field 1], '') as Field1
, IsNull(p.[Field 2], '') as Field2
, r.form_id
, r.userid
from
(
select ri.reg_id
, ri.field_value
, ff.form_id
, ff.label
from #registration_info ri
inner join #form_field ff
on ri.form_field_id = ff.form_field_id
) riff
pivot
(
max(field_value)
for label in ([Field 1], [Field 2])
) p
JOIN #registration r
on p.form_id = r.form_id
AND p.reg_id = r.reg_id
Вот sqlfiddle с рабочей версией.
ДИНАМИЧНЫЙ ПИВОТ
Эта версия сначала получит список полей, а затем развернет их.
create table form
(
form_id int,
form_name varchar(50)
)
create table form_field
(
form_field_id int,
form_id int,
label varchar(50)
)
create table registration
(
reg_id int,
form_id int,
userid int
)
create table registration_info
(
reg_id int,
form_field_id int,
field_value varchar(50)
)
insert into form values(500, 'Custom Form 1')
insert into form_field values(1, 500, 'Field 1')
insert into form_field values(2, 500, 'Field 2')
insert into registration values(23, 500, 45)
insert into registration values(24, 500, 98)
insert into registration_info values(23, 1, 'My Name')
insert into registration_info values(24, 2, 'My City')
DECLARE @cols AS VARCHAR(MAX),
@query AS VARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.label)
FROM dbo.form_field c
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT r.reg_id, ' + @cols + ', r.form_id, r.userid from
(
select ri.reg_id
, ri.field_value
, ff.form_id
, ff.label
from registration_info ri
inner join form_field ff
on ri.form_field_id = ff.form_field_id
) riff
pivot
(
max(field_value)
for label in (' + @cols + ')
) p
JOIN registration r
on p.form_id = r.form_id
AND p.reg_id = r.reg_id'
execute(@query)