Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 917
  • Last Modified:

Pivot Unpivot

How do i pivot/unpivot the follwoing result

month column1 column2
----- ------- -------
jan     1            33      
feb            3            33      
mar            33            22      

to

columns            jan            feb            mar
column1            1            3            33
colum2            33            33            22
0
suryajandhyala
Asked:
suryajandhyala
  • 2
1 Solution
 
Kevin CrossChief Technology OfficerCommented:
+First you have to get column1 and column2 in your data.
+Then pivot by the month column which will group on the column names
(this requires hardcoded column names for JAN, FEB, MAR, ...)


;WITH myCTE AS (
SELECT 'Column1' AS Columns, [month], column1 AS [value]
UNION ALL
SELECT 'Column2', [month], column2
)
SELECT columns,[jan],[feb],[mar]
FROM myCTE
PIVOT (SUM([value]) FOR [month] IN ([jan],[feb],[mar])) p

Open in new window

0
 
suryajandhyalaAuthor Commented:
Thanks a lot.
0
 
Kevin CrossChief Technology OfficerCommented:
>>Grading Comments: Thanks a lot.

You are most welcome.
0

Featured Post

NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now