user1697063
user1697063

Reputation: 157

How do I pivot my data using a T-SQL query

I need to pivot my data so that the classification and Trade appear as headers. Below is an an example dataset.

Description Status Issue_number Custom_Label Custom_Value
Hydraulic Open 680 Classification Major
Hydraulic Open 680 Trade Pumps
Electrical Closed 681 Classification Minor
Electrical Closed 681 Trade Electrical

This is my required output:

Description Status Issue_number Classification Trade
Hydraulic Open 680 Major Pumps
Electrical Closed 681 Minor Electrical

Upvotes: 0

Views: 31

Answers (1)

John Cappelletti
John Cappelletti

Reputation: 81930

A simple PIVOT should do the trick

Select *
 From  YourTable 
 Pivot ( max( Custom_Value ) for Custom_Label in ( [Classification],[Trade] ) ) pvt

EDIT -

Just in case you have extra columns not listed above... you need to "feed" the pivot with only the required columns.

Select *
 From  ( Select Description
               ,Status
               ,Issue_number
               ,Custom_Label
               ,Custom_Value
         From  YourTable
        ) src
 Pivot ( max( Custom_Value ) for Custom_Label in ( [Classification],[Trade] ) ) pvt

Upvotes: 1

Related Questions