将一行中的多行结果分组

时间:2013-02-15 15:05:13

标签: sql sql-server sql-server-2008 tsql

下面的查询给出了两个结果,其中除最后一列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 

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 ;