Solved

Pivot Query

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

I have written a PowerShell script to "walk" the security structure of each SQL instance to find:         Each Login (Windows or SQL)             * Its Server Roles             * Every database to which the login is mapped             * The associated "Database User" for this …
If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

708 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

16 Experts available now in Live!

Get 1:1 Help Now