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

x
?
Solved

create pivot

Posted on 2014-02-17
3
Medium Priority
?
225 Views
Last Modified: 2014-02-17
Hello Experts,

How I can achieve my desired pivot?

Please refer to the attached image.

pivotsample

Thanks.
0
Comment
Question by:JimiJ13
  • 2
3 Comments
 
LVL 66

Accepted Solution

by:
Jim Horn earned 2000 total points
ID: 39864709
Here you go.  Copy the below code and paste in SSMS, then execute, then modify to meet your needs.

Using PIVOT and UNPIVOT

Limitation: The 0-4 are hard-coded, so if you ever have more than 4 you'll have to manually add that to the T-SQL.
CREATE TABLE #pivot (id int, msg varchar(50))

INSERT INTO #pivot (id, msg) 
VALUES 
   (0, 'message content 1'), 
   (1, 'message content 2'), 
   (2, 'message content 3'), 
   (3, 'message content 4'), 
   (4, 'message content 5') 

SELECT 'Message Content' AS message_content, 
[0], [1], [2], [3], [4]
FROM
(SELECT id, msg
    FROM #pivot) AS pvt
PIVOT 
(
MIN(msg)
FOR id IN ([0], [1], [2], [3], [4])
) AS PivotTable;

Open in new window

0
 

Author Closing Comment

by:JimiJ13
ID: 39865727
Thank you for a quick solution and for pointing me to right reference.
0
 
LVL 66

Expert Comment

by:Jim Horn
ID: 39865760
Thanks for the grade.  Good luck with your project.  -Jim
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is basically a blog post I wrote recently. I've found that SARGability is poorly understood, and since many people don't read blogs, I figured I'd post it here as an article. SARGable is an adjective in SQL that means that an item can be fou…
There have been several questions about Large Transaction Log Files in SQL Server 2008, and how to get rid of them when disk space has become critical. This article will explain how to disable full recovery and implement simple recovery that carries…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

926 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question