Click here to Skip to main content
13,895,532 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


7 bookmarked
Posted 22 Apr 2018
Licenced CPOL

How Easily You Can Unpivot the Pivot Data in SQL Server?

, 22 Apr 2018
Rate this:
Please Sign up or sign in to vote.
How to easily unpivot pivot data in SQL Server

I know when we talk about pivoting & unpivoting the data, then most of the time, we are making faces and we feel it would be a tough task. Trust me, after reading this post, you feel unpivot is super easy.

Before jumping directly into unpivot, you might want to share pivot link to take a glimpse if you are not aware of it.

Pivot in SQL Server pivot.

Now, let us assume that we have the following table of employee with id, name, weekid and Dayname columns.

DECLARE @tblEmployeeDayWiseAttendace AS TABLE (Id INT IDENTITY(1,1),
EmployeeName VARCHAR(100),
Tuesday TINYINT,
Wednesday TINYINT,
Thursday TINYINT,
Saturday TINYINT,

Now let’s insert few rows into it:

INSERT INTO @tblEmployeeDayWiseAttendace _

If you run SELECT * FROM @tblEmployeeDayWiseAttendace, then you will get the following data as shown in the below image:

Pivot table indiandotnet

Now, the challenge is to Convert Columns Monday, Tuesday, Wednesday and other day columns to row corresponding to employee and show their value.

To make it very easy, you have to write below CROSS APPLY query:

SELECT tmp.Id, tmp.EmployeeName,tmp.WeekId,tmp2.weekdayname,tmp2.weekValue
FROM @tblEmployeeDayWiseAttendace tmp 
CROSS APPLY(values(‘Monday’,tmp.Monday),

Once you run this query, you will get the output which you require.

Now, tell me, are you still afraid of unpivot.

Share your thoughts & inputs in the comments below.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Technical Lead
India India
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190306.1 | Last Updated 23 Apr 2018
Article Copyright 2018 by Rajat-Indiandotnet
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid