Вы можете попробовать использовать PIVOT - он будет работать на сервере sql
with cte as
(
select mainId,secondaryId,row_number() over(partition by mainid order by secondaryid) as rn
from tablename
)
select mainid, pv* from
cte pivot(max(secondaryid) for rn in ([1],[2],[3]))
или Вы можете попробовать использовать условное агрегирование
select mainid, max(case when rn=1 then secondaryid) as secondaryid_01,
max(case when rn=2 then secondaryid) as secondaryid_02,
max(case when rn=3 then secondaryid) as secondaryid_03
from cte
group by mainid