你可以使用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 Fiddle
更新:
如果有需要我會做這樣的,而不是更多的領域。
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
我不認爲這是可能的,因爲數量結果中的列將根據組中用戶的數量進行更改。爲什麼不使用簡單的內部連接將其顯示爲每行用戶? –
不,列的數量總是相同(5),因爲每個組的用戶不會超過3個。我需要這種佈局,因爲業務特定的應用程序。 –
我會盡快回復您。但你能告訴我最大不。在IDGroup中的ID。 – Luv