0

下面的查询给了我两个结果,除了最后一列 v2_roles.id 之外,一切都相同。有没有办法将它们分组在一列中(可能是逗号分隔的列表)并只得到一个结果

SELECT v2_admin.adminid, 
       v2_admin.adminname, 
       v2_admin.login, 
       v2_admin.email, 
       v2_roles.id 
FROM   v2_admin 
       INNER JOIN v2_admin_roles 
               ON v2_admin.adminid = v2_admin_roles.adminid 
       INNER JOIN v2_roles 
               ON v2_admin_roles.roleid = v2_roles.id 
WHERE  v2_admin.adminid = 2 
4

2 回答 2

1

这是一个小技巧,FOR XML用于将字段转换为列表并STUFF删除开头的逗号——这应该很接近(未经测试):

SELECT v2_admin.adminid, 
       v2_admin.adminname, 
       v2_admin.login, 
       v2_admin.email, 
       STUFF(
        (
            SELECT ',' +  CAST(v2_roles.id as varchar) AS [text()]
                FROM v2_roles
                WHERE v2_admin_roles.roleid = v2_roles.id 
            ORDER BY v2_roles.id
            FOR XML PATH('')
        ), 1, 1, '') AS Roles
FROM   v2_admin 
       INNER JOIN v2_admin_roles 
               ON v2_admin.adminid = v2_admin_roles.adminid 
WHERE  v2_admin.adminid = 2 
GROUP BY v2_admin.adminid, 
       v2_admin.adminname, 
       v2_admin.login, 
       v2_admin.email
于 2013-02-15T15:13:44.190 回答
1

这也应该有效,

;WITH mytable AS (
   SELECT v2_admin.adminid, 
       v2_admin.adminname, 
       v2_admin.login, 
       v2_admin.email, 
       v2_roles.id 
   FROM   v2_admin 
       INNER JOIN v2_admin_roles 
               ON v2_admin.adminid = v2_admin_roles.adminid 
       INNER JOIN v2_roles 
               ON v2_admin_roles.roleid = v2_roles.id 
   WHERE  v2_admin.adminid = 2 
)

SELECT t1.adminid,t1.adminname, t1.login, t1.email,
       roleIds =REPLACE( (SELECT convert(varchar,id) AS [data()]
                FROM mytable t2
                WHERE t2.adminid = t1.adminid
                --ORDER BY t2.adminid
                FOR XML PATH('')
            ), ' ', ' , ')
FROM mytable t1
GROUP BY t1.adminid,t1.adminname, t1.login, t1.email ;
于 2013-02-15T15:17:13.027 回答