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

x
?
Solved

T-SQL PIVOT:  Is there any way to do an 'all values' for columns instead of [1], [2], [3], ..., [200]

Posted on 2013-01-23
4
Medium Priority
?
287 Views
Last Modified: 2013-01-28
Hi All

I have a table my_table that has a row_id, column_id, and value.
There are 500 rows and 200 columns, so rows x columns = a rowcount of 100,000.

To flatten all rows, and the first three columns, the below T-SQL works great:
SELECT row_id, [1], [2], [3]
FROM (SELECT row_id, column_id, value FROM my_table WHERE some_fk_id = 0 AND column_id IN (1, 2, 3)) AS src
PIVOT ( MIN(value) FOR column_id IN ([1], [2], [3])) AS tgt

Open in new window

I have 200 columns, and would like to avoid hard-typing [1], [2], [3], ..., [200] in my T-SQL.
Question:  Is there any way in a PIVOT to do an 'all values' for columns?

Thanks in advance.
Jim
0
Comment
Question by:Jim Horn
[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
  • 3
4 Comments
 
LVL 17

Accepted Solution

by:
Barry Cunney earned 2000 total points
ID: 38810392
SELECT  @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT
                                '],[' + t.ColumnName
                        FROM    #Table AS t
                        --ORDER BY '],[' + t.ID
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'

SELECT  @cols

SET @query = N'SELECT ID,'+ @cols +' FROM
(SELECT t1.ID,t1.ColumnName , t1.Value FROM #Table AS t1) p
PIVOT (MAX([Value]) FOR ColumnName IN ( '+ @cols +' ))
AS pvt;'

EXECUTE(@query)
0
 
LVL 66

Author Comment

by:Jim Horn
ID: 38810668
... playing with it ...
0
 
LVL 66

Assisted Solution

by:Jim Horn
Jim Horn earned 0 total points
ID: 38810874
Bingo bango.

Had to change a couple of things in the STUFF to pull this off.

-- TESTING ONLY, set to 0 for production, 1 for extra troubleshooting sets
DECLARE @debug bit = 1

DECLARE @cols VARCHAR(max), @query VARCHAR(max)

SELECT @cols = STUFF((   
	SELECT '[' + CAST(t.column_id as varchar(max)) + '],'
	FROM mrmd.comment_version AS t 
	WHERE cluster_id = 0 AND row_id = 1
	ORDER BY t.column_id
	FOR XML PATH('') ), 1, 0, '') 

SELECT @cols = LEFT(@cols, LEN(@cols) - 1)

IF @debug = 1
	SELECT 'cols', @cols

SET @query = N'
	SELECT row_id, '+ @cols +' 
	FROM ( SELECT row_id, column_id, value FROM mrmd.comment_version WHERE cluster_id = 0) as src 
	PIVOT ( Min(value) FOR column_id IN ( '+ @cols +' )) as pvt' 

IF @debug = 1
	SELECT '@query', @query
	
EXECUTE(@query)
GO

Open in new window

0
 
LVL 66

Author Closing Comment

by:Jim Horn
ID: 38826167
Thanks.
0

Featured Post

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

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

Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

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