Transpose data using T-SQL

Arundhati Sen 151 Reputation points
2022-03-14T15:43:58.763+00:00

How can I pivot table in SQL Server using T-SQL and achieve target data from source data source data : ![182878-image.png][1] target data : ![182942-image.png][2] [1]: /api/attachments/182878-image.png?platform=QnA [2]: /api/attachments/182942-image.png?platform=QnA

Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. LiHong-MSFT 10,056 Reputation points
    2022-03-15T02:47:42.787+00:00

    Hi anonymous user
    If there is an additional strictly increasing identity column in your source data table,then check this query:

    ;WITH CTE1 AS  
    (SELECT * FROM (SELECT Field,Value FROM Source_Table WHERE Field IN('Application Name','Application Form','Application Type','Application Version'))S  
              PIVOT(MAX(Value)FOR Field IN([Application Name],[Application Form],[Application Type],[Application Version]))P  
    ),CTE2 AS  
    (SELECT * FROM (SELECT Field,Value,ROW_NUMBER()OVER(PARTITION BY Field ORDER BY identity_column)AS RNum FROM Source_Table WHERE Field IN('Finding Ref No','Port','Prepared','Project'))S  
              PIVOT(MAX(Value)FOR Field IN([Finding Ref No],[Port],[Prepared],[Project]))P  
    )  
    SELECT CTE1.*,[Finding Ref No],[Port],[Prepared],[Project]  
    FROM CTE1 CROSS JOIN CTE2  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2022-03-14T22:27:27.613+00:00
    SELECT MIN(CASE field WHEN 'Application Name'  THEN value END) AS "Application name",
        MIN(CASE field WHEN 'Application Form'  THEN value END) AS "Application form",
       --- etc.
    FROM  tbl
    

    If you expected something else, see Yithzak's comment.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.