基于varchar字段的逗号分隔输出

时间:2014-06-13 10:06:12

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

我有这个 SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE AccessUser
(
    AccessUserID int, 
    AccessUserName varchar(255), 
    AccessUserType int, 
    AccessUserGroups varchar(255)
);

INSERT INTO AccessUser
(   AccessUserID, 
    AccessUserName, 
    AccessUserType, 
    AccessUserGroups
)
VALUES
    (1, 'Group 1', 2, ''),
    (2, 'Group 2', 2, ''),
    (3, 'John', 5, '@1@'),
    (4, 'Nick', 5, '@1@@2@');

查询1

SELECT DISTINCT
Empl.AccessUserName AS Name,
Firm.AccessUserName AS FirmName
FROM AccessUser AS Firm, AccessUser AS Empl
WHERE Empl.AccessUserType = 5
AND Empl.AccessUserGroups LIKE ('%@' + CAST(Firm.AccessUserID AS VARCHAR(10)) + '@%')
ORDER BY Empl.AccessUserName ASC

Results

| NAME | FIRMNAME |
|------|----------|
| John |  Group 1 |
| Nick |  Group 1 |
| Nick |  Group 2 |

问题:如何修改查询,输出:

| NAME |      FIRMNAME      |
|------|--------------------|
| John |  Group 1           |
| Nick |  Group 1, Group 2  |

如果用户有多个AccessUserGroups,我想要做的就是对公司名称进行commaseparate。 甚至可以在一个查询中这样做吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

WITH CTE AS
(SELECT DISTINCT
Empl.AccessUserName AS Name,
Firm.AccessUserName AS FirmName
FROM AccessUser AS Firm, AccessUser AS Empl
WHERE Empl.AccessUserType = 5
AND Empl.AccessUserGroups LIKE ('%@' + CAST(Firm.AccessUserID AS VARCHAR(10)) + '@%'))

SELECT Name,
      FirmName = STUFF((
          SELECT ',' + convert(varchar(10),T2.FirmName)
          FROM CTE T2
          WHERE T1.Name = T2.Name
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM CTE T1
GROUP BY Name
ORDER BY FirmName

结果:

NAME    FIRMNAME
John    Group 1
Nick    Group 1,Group 2

Fiddle Demo