SQL将多行组合成一个逗号分隔列

时间:2015-07-16 02:43:51

标签: sql sql-server

我试图从asp.net会员表中获取用户列表。

我想在一行中显示用户ID,用户名,电子邮件和角色名称。

我的陈述如下

SELECT [Dev].[dbo].[aspnet_Users].[UserId],
  [UserName],
  [Email],
  [RoleName]

FROM [Dev].[dbo].[aspnet_Users]

INNER JOIN [Dev].[dbo].[aspnet_Membership]

ON [Dev].[dbo].[aspnet_Users].[UserId] = [Dev].[dbo].[aspnet_Membership].[UserId]

INNER JOIN [Dev].[dbo].[aspnet_UsersInRoles]

ON [Dev].[dbo].[aspnet_Users].[UserId] = [Dev].[dbo].[aspnet_UsersInRoles].[UserId]

Inner Join [Dev].[dbo].[aspnet_Roles]

On [Dev].[dbo].[aspnet_UsersInRoles].[RoleId] = [Dev].[dbo].[aspnet_Roles].[RoleId]

我得到的结果接近我想要的结果,除了我为角色名称获得多行。

| UserID | UserName | Email | RoleName |
|--------|----------|-------|----------|
| 1      | Jon      | Jon@  | Author   |
| 1      | Jon      | Jon@  | Approver |
| 1      | Jon      | Jon@  | Admin    |
| 2      | Mary     | Mary@ | Author   |
| 2      | Jon      | Mary@ | Approver |

如何将多行名称显示为一行?

| UserID | UserName | Email | RoleName                  |
|--------|----------|-------|---------------------------|
| 1      | Jon      | Jon@  | Author, Approver, Admin   |
| 2      | mary     | mary@ | Author, Approver          |

0 个答案:

没有答案