由于您使用的是 SQL Server,因此您可以同时使用UNPIVOT
和PIVOT
函数来转换此数据。如果您知道您将拥有多少个值,那么您可以对这些值进行硬编码,如下所示:
select *
from
(
select urn,
value,
col +'_'+ CAST(rn as varchar(10)) as col
from
(
SELECT M.urn,
cast(M.eventdate as varchar(50)) eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
cast(N.time as varchar(50)) time,
ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
AND M.eventcode = 'TFRADMIN'
) src1
unpivot
(
value
for col in (eventdate, eventlocation, eventroom, eventbed, time)
) unpiv
) src2
pivot
(
max(value)
for col in ([eventdate_1], [eventlocation_1], [eventroom_1], [eventbed_1], [time_1],
[eventdate_2], [eventlocation_2], [eventroom_2], [eventbed_2], [time_2],
[eventdate_3], [eventlocation_3], [eventroom_3], [eventbed_3], [time_3])
) piv
注意 - 未经测试
如果您有未知数量的列,那么您可以使用类似于这样的动态 sql:
DECLARE @query AS NVARCHAR(MAX),
@colsPivot as NVARCHAR(MAX)
select @colsPivot = STUFF((SELECT ','
+ quotename(c.name +'_'+ cast(t.rn as varchar(10)))
from
(
select ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.eventseqno
AND M.eventdate = N.eventdate
WHERE M.urn = 'F1002754364'
) t
cross apply sys.columns as C
where C.object_id IN (object_id('admpatevents'), object_id('admpattransferindex')) and
C.name not in ('urn') -- add any other columns your want to exclude
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select *
from
(
select urn, value, col +''_''+ CAST(rn as varchar(10)) as col
from
(
SELECT M.urn,
cast(M.eventdate as varchar(20)) eventdate,
M.eventlocation,
M.eventroom,
M.eventbed,
cast(N.time as varchar(20)) time,
ROW_NUMBER() over(PARTITION by m.urn order by m.eventdate) rn
FROM admpatevents M
INNER JOIN admpattransferindex N
ON M.urn = N.urn
AND M.eventseqno = N.EVENTseqno
AND M.eventdate = N.eventdate
WHERE M.urn = ''F1002754364''
) x
unpivot
(
value
for col in (eventdate, eventlocation, eventroom, eventbed, time)
) u
) x1
pivot
(
max(value)
for col in ('+ @colspivot +')
) p'
exec(@query)
请参阅带有演示的 SQL Fiddle