tsql左外部联接,在一行上显示多个记录
嗨,我有两个1-N关系的表,其中N最大为3。一个组至少有1个用户,最多有3个用户。我想用select查询在一行上显示组和所有可能的用户 组:tsql左外部联接,在一行上显示多个记录,sql,tsql,sql-server-2005,Sql,Tsql,Sql Server 2005,嗨,我有两个1-N关系的表,其中N最大为3。一个组至少有1个用户,最多有3个用户。我想用select查询在一行上显示组和所有可能的用户 组: ID Name 1 Group1 2 Group2 用户: ID Username IDGroup 1 User1 1 2 User2 2 3 User3 1 4 User4 1 结果(没有用户名显示为ok null或空字符串): 你可以用 更新: 如果需要更多的字段,我会这样做 select T.
ID Name
1 Group1
2 Group2
用户:
ID Username IDGroup
1 User1 1
2 User2 2
3 User3 1
4 User4 1
结果(没有用户名显示为ok null或空字符串):
你可以用
更新:
如果需要更多的字段,我会这样做
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
我还想提供这个答案,因为它也很好,而且在我看来,如果您想添加其他字段,它更灵活:
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
我认为这是不可能的,因为结果中的列数将根据组中的用户数进行更改。为什么不使用简单的内部联接将其显示为每行的每个用户?否列的数量将始终相同(5),因为每个组的用户不超过3个。我需要这个布局是因为一个特定于业务的应用程序。我会给你回复的。但是你能告诉我一个ID组的最大ID数吗?谢谢!是的,每个组最多3个用户(如果可以显示此组中的前3个用户,而不考虑组中可能的用户数),我已提交了一个类似的。谢谢你,我以前从未听说过pivot,它是一个真正的救命软件!非常感谢!如果你不介意的话,我再问你一个问题。我在用户表中还有一个电子邮件字段。我如何使用pivot将其显示给用户名?@Arno2501好的,我看到您已经将其排序为+1。
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
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