Answers for "Please suggest way to convert group of row values to columns"
https://ask.sqlservercentral.com/questions/146954/please-suggest-way-to-convert-group-of-row-values.html
The latest answers for the question "Please suggest way to convert group of row values to columns"Answer by Oleg
https://ask.sqlservercentral.com/answers/146971/view.html
I will assume that there is a table, let's call it YourTable, which has 3 columns: DUNS, [Owner], and AccountIds. For each DUNS, [Owner] combination there may be multiple rows, each with different AccountIds value, and the number of such rows is unknown. Should such maximum number of rows (which determines the number of pivoted columns) be known, the standard static script could be used to pivot the data. Let's say that we know that the number is 5. Then the following select may be used:
-- static pivot, this may be used if the number of pivoted columns is known
select
*
from (
select
DUNS, [Owner], AccountIds,
row_number() over (partition by DUNS, [Owner] order by AccountIds) n
from YourTable
) src
pivot (max(AccountIds) for n in ([1], [2], [3], [4], [5])) pvt;
It is easy to see that the only part of the script which needs to change is the part listing the numbers. So, in order to generate the script which will work for any number of pivoted columns, something like this may be used:
-- dynamic script, needs to be used if the number of columns is not known
declare @columnList nvarchar(max) = stuff((
select
top (select top 1 count(1) from YourTable group by DUNS, [Owner] order by 1 desc)
', ' + quotename(row_number() over (order by (select null))) from YourTable
for xml path('')
), 1, 2, '');
-- print @columnList;
declare @sql nvarchar(max) = '
select
*
from (
select
DUNS, [Owner], AccountIds,
row_number() over (partition by DUNS, [Owner] order by AccountIds) n
from YourTable
) src
pivot (max(AccountIds) for n in (' + @columnList + ')) pvt;
';
-- print @sql;
exec sp_executesql @statement = @sql;
go
Please uncomment the commented out print statements to see what is being generated. Based on the sample data in question, this dynamic pivot script produces the following results:
DUNS Owner 1 2 3
----------- ----- ---- ---- ----
1 a s t u
2 b v w NULL
3 c x y NULL
Hope this helps.
OlegFri, 20 Apr 2018 15:52:05 GMTOleg