SQL Server将多行和两列分成多行的单行

时间:2016-10-17 15:50:00

标签: sql sql-server pivot

我有一个表格,其中包含案例ID,操作和原因的列。 单个案例ID可以包含多个具有不同操作和代码的行。我可以使用列action1,action2,action3等进行数据转换并获取多行,但是对于我的生活,不能在单行上获取case id,action1,reason1,action2,reason2等。

1 个答案:

答案 0 :(得分:0)

如果你需要更有活力(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)

返回

enter image description here