使用sql server 2008,我需要一个查询来显示以下结果
User_Name Group_Name Checked
user1 Lead 0
user1 Admin 1
user1 Supervisor 0
user1 Monitor 0
user2 Lead 0
user2 Admin 0
user2 Supervisor 1
user2 Monitor 1
我有4个组(Lead,Admin,Supervisor,monitor),链接表是User Group。如何为每个用户显示所有组(如上所示)?如果为用户选中了组,它将显示在用户组中,如果未选中则显示在表格中。
表格:
用户:
User_ID int
User_Name nvarchar
Email nvarchar
组:
Group_ID int
Group_Name nvarchar
用户组:
User_ID int,
Group_ID int
答案 0 :(得分:1)
试试这个:
select User.User_Name, Group.Group_Name,
case when UserGroup.User_ID is null then 0 else 1 end as Checked
from User cross join Group
left join UserGroup on User.User_ID = UserGroup.User_ID
and Group.Group_ID = UserGroup.Group_ID
答案 1 :(得分:0)
在SQL Server 2005+中,您可以使用APPLY
运算符,它将每个group
值分配给每个user
,然后您就可以加入usergroup
表:< / p>
select u.user_name,
g.group_name,
case when ug.user_id is not null then 1 else 0 end Checked
from [user] u
cross apply [group] g
left join usergroup ug
on u.user_id = ug.user_id
and g.group_id = ug.group_id