Hi,
I have this data:
---------------------------------
|Masterarticle | childarticle |
----------------------------------
| 12341 | 12345 |
| 12341 | 12346 |
| 12341 | 12347 |
| 12342 | 44875 |
| 12342 | 44876 |
----------------------------------
and this is my expected resultset:
| 12341 | 12342 |
-------------------------
| 12345 | 44875 |
-------------------------
| 12346 | 44876 |
-------------------------
| 12347 | NULL |
-------------------------
| 12347 | NULL |
-------------------------
I have this, but it shows me only one row, because of the aggregate max(childarticle). Is there any way, to query a dynamic table whitout aggregate?
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Masterarticle)
from table
group by Masterarticle
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select childarticle, Masterarticle
from table
) x
pivot
(
max(childarticle)
for Masterarticle in (' + @cols + N')
) p '
exec sp_executesql @query;