I solved it this way:declare @t table(desc1 varchar(50), desc2 varchar(50), category varchar(50))insert into @t(desc1, desc2, category) values('bag' ,'fancybag for children' ,'children'),('wallet', 'wallets for women', 'women'),('scarf','tutuya scarf','children')select case rn when 1 then '<category=' + category + '>' + char(10) + '<h1>' + desc1 + '</h1>' + char(10) + '<div>' + desc2 + '</div>' else '<h1>' + desc1 + '</h1>' + char(10) + '<div>' + desc2 + '</div>' endfrom( select rn = ROW_NUMBER() over(partition by category order by desc1, desc2) , category , desc1 , desc2 from @t t) torder by category, desc1, desc2