Solved

Pivot Query

Posted on 2013-11-17
1
215 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 40

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

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

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

Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
This is an introductory video for CloudBerry Managed Backup. You will learn how to sign up with the service and get started in a few minutes.
Send secure, cloud-based, encrypted alerts and maintain HIPAA compliant messaging. Integrates priority & secure messaging into one application. Ensures IT, emergency respondents and healthcare professionals that their critical messages are never mis…

911 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now