1

嗨,我有两个具有 1-N 关系的表,其中 N 最大为 3。一个组至少有 1 个用户,最多有 3 个用户。我想使用选择查询在单行上显示组和所有可能的用户。

团体 :

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
4

2 回答 2

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小提琴

更新:

如果需要更多字段,我会这样做。

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
于 2013-04-02T08:37:28.873 回答
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
于 2013-04-02T10:04:32.610 回答