0

这是我的桌子:

CaseID                                AttributeName  AttributeValue
03E07546-9C10-4399-B840-04F9CE211FB8  Case Title     deepa04
03E07546-9C10-4399-B840-04F9CE211FB8  Body Part      hand
03E07546-9C10-4399-B840-04F9CE211FB8  Diagnosis      123
E999866E-E8BE-4442-8A87-C419D482022E  Case Title     deep_case
E999866E-E8BE-4442-8A87-C419D482022E  Body Part      leg
E999866E-E8BE-4442-8A87-C419D482022E  Diagnosis      123

我需要将其转换为:

CaseID                                Case Title  Body Part  Diagnosis
03E07546-9C10-4399-B840-04F9CE211FB8  deepa04     hand       123
E999866E-E8BE-4442-8A87-C419D482022E  deep_case   leg        123

如何在 SQL Server 2008 中使用动态数据透视函数来实现这一点?

4

2 回答 2

1

试试tihis:

select CaseID  ,   [Case Title],[Body Part],  Diagnosis
from <your_table>
PIVOT (MAX(AttributeValue) FOR AttributeName IN 
([Case Title],[Body Part],  Diagnosis)) P 

Edit1: 如果列名称是动态的,您可以这样做

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(AttributeName) 
                    from <your_table>
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')



set @query = 'SELECT CaseID  , ' + @cols + ' from t_case
             pivot 
            (
                MAX(AttributeValue)
                for AttributeName in (' + @cols + ')
            ) p '
print(@query)
execute(@query)
于 2012-08-08T06:33:02.473 回答
0

这就是你可以使用的方式pivot

select P.CaseID, P.[Case Title], P.[Body Part], P.Diagnosis
from (
     select CaseID, AttributeName, AttributeValue
     from YourTable
     ) as T
pivot (
      min(AttributeValue) 
      for AttributeName in ([Case Title], [Body Part], [Diagnosis])
      ) as P
于 2012-08-08T06:31:58.133 回答