0

This is my table:

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

I need to convert this into:

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

How can I achieve this using dynamic pivot functions in SQL Server 2008?

1

2 Answers 2

1

try tihis:

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

Edit1: If column Names are Dynamic You could do this

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)
Sign up to request clarification or add additional context in comments.

8 Comments

but Case Title,Body Part,Diagnosis are dynamic values,in that case what we do?
Then we can do a dynamic pivot query
The column name we can store in a variable and the use it in the query
@Jeffreykalampukattussery: I have updated my answer , Plz check it
thanks for that joe,but [Body Part],[Case Title],[Diagnosis],[DOB],[History],[Keywords],[Modality],[Sex] from t_case getting error "Invalid object name 't_case'." t_case is a temperory table,does dat making the error
|
0

This is how you can use 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

1 Comment

but Case Title,Body Part,Diagnosis are dynamic values,in that case what we do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.