Solved

Pivot Query

Posted on 2013-11-17
1
219 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
1 Comment
 
LVL 41

Accepted Solution

by:
Sharath earned 500 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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

Suggested Solutions

Long way back, we had to take help from third party tools in order to encrypt and decrypt data.  Gradually Microsoft understood the need for this feature and started to implement it by building functionality into SQL Server. Finally, with SQL 2008, …
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

679 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