您可以使用Pivot。
select P.IDGroup,
P.GroupName,
P.[1] as Username1,
P.[2] as Username2,
P.[3] as Username3
from
(
select G.ID as IDGroup,
G.Name as GroupName,
U.Username,
row_number() over(partition by G.ID order by U.Username) as rn
from Groups as G
left outer join Users as U
on G.ID = U.IDGroup
) as T
pivot
(
max(T.Username) for T.rn in ([1],[2],[3])
) as P
SQL小提琴
更新:
如果需要更多字段,我会这样做。
select T.IDGroup,
T.GroupName,
max(case when T.rn = 1 then T.Username end) as Username1,
max(case when T.rn = 1 then T.Email end) as Email1,
max(case when T.rn = 2 then T.Username end) as Username2,
max(case when T.rn = 2 then T.Email end) as Email2,
max(case when T.rn = 3 then T.Username end) as Username3,
max(case when T.rn = 3 then T.Email end) as Email3
from (
select G.ID as IDGroup,
G.Name as GroupName,
U.Username,
U.Email,
row_number() over(partition by G.ID order by U.Username) as rn
from Groups as G
left outer join Users as U
on G.ID = U.IDGroup
) as T
group by T.IDGroup,
T.GroupName