2013-04-02 21 views
1

嗨,我有兩個表,其中N是最大值3的一個關係。一個組至少有一個用戶和最多3個用戶。我想通過選擇查詢在單行顯示組和所有可能的用戶。tsql左外部連接,在一條線上顯示多條記錄

組:

ID Name 
1 Group1 
2 Group2 

用戶:

ID Username IDGroup 
1 User1 1 
2 User2 2 
3 User3 1 
4 User4 1 

結果(如果沒有用戶名,以顯示它的確定爲空或空字符串):

IDGroup GroupName Username1 Username2 Username3 
1  Group1 User1  User3  User4 
2  Group2 User2  Null  Null 
+0

我不認爲這是可能的,因爲數量結果中的列將根據組中用戶的數量進行更改。爲什麼不使用簡單的內部連接將其顯示爲每行用戶? –

+0

不,列的數量總是相同(5),因爲每個組的用戶不會超過3個。我需要這種佈局,因爲業務特定的應用程序。 –

+0

我會盡快回復您。但你能告訴我最大不。在IDGroup中的ID。 – Luv

回答

2

你可以使用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 
+0

謝謝你我從來沒有聽說過關鍵,它是一個真正的生活保護者!謝謝一堆! –

+0

如果你不介意,還有一個問題。我在用戶表中還有一個電子郵件字段。我怎麼會顯示這另外的用戶名使用樞軸? –

+0

@ Arno2501好的,我看到你已經有了一個排序,然後+1。 –

1

我也想提供這個答案,因爲它也不錯,在我看來更靈活,如果你想增加額外的字段:

select 
     T.IDGroup 
     ,T.GroupName 
     ,[1] = max(case when rn = 1 then T.Username end) 
     ,[2] = max(case when rn = 2 then T.Username end) 
     ,[3] = max(case when rn = 3 then T.Username end) 
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 
group by T.IDGroup, T.GroupName