もう少しダイナミック(N理由から)行く必要がある場合は
Drop Table #Temp
Declare @YourTable table (ID int,Action varchar(50),Reason varchar(50))
Insert Into @YourTable values
(1,'Load Data','Boss said to'),
(1,'Run Query','It is what I do'),
(2,'Take Garbage Out','Wife makes me')
-- Convert Data to EAV Structure'ish
Declare @XML xml = (Select *,GrpSeq = Row_Number() over (Partition By ID Order By (Select NULL)) from @YourTable for XML RAW)
Select ID = r.value('@ID','int')
,ColSeq = Row_Number() over (Partition By r.value('@ID','int') Order By (Select NULL))
,Element = attr.value('local-name(.)','varchar(100)')+r.value('@GrpSeq','varchar(10)')
,Value = attr.value('.','varchar(max)')
Into #Temp
From @XML.nodes('/row') as A(r)
Cross Apply A.r.nodes('./@*') AS B(attr)
Where attr.value('local-name(.)','varchar(100)') not in ('ID','GrpSeq')
-- Get Cols in correct Order
Declare @Cols varchar(max)
Set @Cols = Stuff((Select ',' + QuoteName(Element)
From (Select Distinct Top 100 Percent ColSeq,Element From #Temp Order By ColSeq) A
For XML Path(''), Type
).value('.', 'varchar(max)'),1,1,'')
-- Execute Dynamic Pivot
Declare @SQL varchar(max) = '
Select *
From (Select ID,Element,Value From #Temp) T
Pivot (
max(Value)
For [Element] in (' + @Cols + ')
) P '
Exec(@SQL)
戻り
可能な重複:https://stackoverflow.com/questions/2170058/can- sql-server-pivot-without-knowingという結果の列名 – openshac