Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Pivot Query

Posted on 2013-11-17
1
Medium Priority
?
222 Views
Last Modified: 2013-11-17
Can someone help me with a pivot query for the attached dataset.

Thanks in advance.
primarykeys.xlsx
0
Comment
Question by:sherbug1015
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 41

Accepted Solution

by:
Sharath earned 2000 total points
ID: 39655122
If you know the number of positions, you can try like this.
SELECT TableName, 
       [1] as primarykeycolumn1,
	   [2] as primarykeycolumn2,
	   [3] as primarykeycolumn3
  FROM Test
 PIVOT (MAX(primarykeycolumn1) FOR position IN ([1],[2],[3])) AS p

Open in new window


if the no. of positions are unknown, you can try dynamic sql.
DECLARE @sql VARCHAR(8000),@select VARCHAR(8000)
SET @sql = (SELECT DISTINCT ',[' + CONVERT(NVARCHAR(10),position) + ']' from Test for xml PATH('')) 
SET @select = (SELECT DISTINCT ',[' + CONVERT(NVARCHAR(10),position) + '] AS primarykeycolumn' + CONVERT(NVARCHAR(10),position) from Test for xml PATH('')) 
SET @sql = '
SELECT TableName' + @select + '
  FROM Test
 PIVOT (MAX(primarykeycolumn1) FOR position IN (' + SUBSTRING(@sql,2,LEN(@sql)) + ')) AS p'
EXEC(@sql)

Open in new window


http://sqlfiddle.com/#!3/53bc8/18
http://sqlfiddle.com/#!3/53bc8/16
0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

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

     When we have to pass multiple rows of data to SQL Server, the developers either have to send one row at a time or come up with other workarounds to meet requirements like using XML to pass data, which is complex and tedious to use. There is a …
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…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

721 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