December 2, 2004 at 8:03 am
I have an intermediate result (a virtual table) which looks like this:
NumberInAgeGroup AgeGroupName
102 youngsters
504 middleaged
706 retired
I need to pivot this output and get the AgeGroupName as columnheader to
NumberInAgeGroup.
Thus:
youngsters middleaged retired
102 504 706
Ideas?
/m
December 3, 2004 at 1:41 am
Hello /m
Maybe like this?
Create Table #tmpAgeGroups (NumberInAgeGroup int, AgeGroupName varchar(15))
Insert into #tmpAgeGroups (NumberInAgeGroup, AgeGroupName)
Values(102, 'youngsters')
Insert into #tmpAgeGroups (NumberInAgeGroup, AgeGroupName)
Values(504, 'middleaged')
Insert into #tmpAgeGroups (NumberInAgeGroup, AgeGroupName)
Values(706, 'retired')
Declare @LastGroup varchar(15)
Declare @sql nvarchar(4000)
set @sql = ''
Set @LastGroup = (Select top 1 AgeGroupName From #tmpAgeGroups Order By AgeGroupName)
While @LastGroup is not null
Begin
If len(@SQL)> 0 Set @sql = @sql + ', '
Set @sql = @sql + '(SELECT ' + @LastGroup + '=NumberInAgeGroup From #tmpAgeGroups Where AgeGroupName = ''' + @LastGroup + ''') ' + @LastGroup
Set @LastGroup = (Select top 1 AgeGroupName From #tmpAgeGroups Where AgeGroupName > @LastGroup Order By AgeGroupName)
End
If len(@SQL)> 0
Begin
Set @sql = 'SELECT * FROM ' + @sql
Exec sp_Executesql @sql
End
Drop Table #tmpAgeGroups
Regards,
Leon Bakkers
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply