I have the following data:
DECLARE @DataSource TABLE
(
[ColumnA] INT
,[ColumnB] INT
,[ColumnC] INT
)
INSERT INTO @DataSource ([ColumnA], [ColumnB], [ColumnC])
VALUES (5060,1006,100118)
,(5060,1006,100119)
,(5060,1006,100120)
,(5060,1007,100121)
,(5060,1007,100122)
,(5060,1012,100123)
SELECT [ColumnA]
,[ColumnB]
,[ColumnC]
FROM @DataSource
and I need to converted like this:
The difficult part is that the data is dynamic (I do not know how many columns I will have) and I am not able to use a standard pivot here because the values in ColumnC
are different and as a result I am going to have as many columns as values appears in ColumnC
.
Is there any technique to achieve this? Any kind of help (answers, articles, suggestions) will be appreciated.
My suggestion whenever you are working with PIVOT is to alway write the query first with the values hard-coded, then you can easily convert the query to a dynamic solution.
Since you are going to have multiple values of
columnC
that will be converted to columns, then you need to look at using therow_number()
windowing function to generate a unique sequence for eachcolumnc
based on the values ofcolumnA
andcolumnB
.The starting point for your query will be:
See Demo. This query will generate the list of new columns names
SampleTitle1
, etc:You can then apply the pivot on
columnC
with the new column names listed inseq
:See SQL Fiddle with Demo.
Once you have the correct logic, you can convert the data to dynamic SQL. The key here is generating the list of new column names. I typically use
FOR XML PATH
for this similar to:See Demo. Once you have the list of column names, then you will generate your sql string to execute, the full code will be:
See SQL Fiddle with Demo. These give a result: