这是我的表:
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中的动态数据透视功能实现此目的?
答案 0 :(得分:1)
试试这个:
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)
答案 1 :(得分: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