SQL Server 2005 以降を使用している場合、データを転置するためのオプションがいくつかあります。PIVOT
次のような関数を実装できます。
select AID, ASID,
M1 as M1_Date, M2 as M2_Date,
M3 as M3_Date, M4 as M4_Date, M5 as M5_Date
from
(
select AID, ASID, Milestone,
MilestoneDate
from yourtable
where AID = whatever -- other filters here
) src
pivot
(
max(milestonedate)
for milestone in (M1, M2, M3, M4, M5...)
) piv
CASE
または、次のステートメントで集計関数を使用できます。
select aid,
asid,
max(case when milestone = 'M1' then milestonedate else null end) M1_Date,
max(case when milestone = 'M2' then milestonedate else null end) M2_Date,
max(case when milestone = 'M3' then milestonedate else null end) M3_Date,
max(case when milestone = 'M4' then milestonedate else null end) M4_Date
from yourtable
where AID = whatever -- other filters here
group by aid, asid
上記の 2 つのクエリは、値の数がわかっている場合にうまく機能しmilestone
ます。そうでない場合は、動的SQLを実装してデータを転置できます。動的バージョンは次のようになります。
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX),
@colNames AS NVARCHAR(MAX),
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Milestone)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colNames = STUFF((SELECT distinct ',' + QUOTENAME(Milestone+'_Date')
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT AID, ASID,' + @colNames + ' from
(
select AID, ASID, Milestone,
MilestoneDate
from yourtable
where AID = whatever -- other filters here
) x
pivot
(
max(MilestoneDate)
for Milestone in (' + @cols + ')
) p '
execute(@query)