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 FiddlewithDemoを参照してください