T-SQL - 仅限某些组的CSV

时间:2015-08-21 08:38:06

标签: sql sql-server xml csv

示例数据:

ID Name   Role
1  Jack   Manager
2  John   Manager
3  James  Employee
4  Helen  Employee
5  Tony   Manager
6  Louise Employee

我怎么能回来:

Name               Role
Jack, John, Louise Manager
James              Employee
Helen              Employee
Louise             Employee

我想我只需要在特定组中使用带有XML的STUFF。请指教。

然后我需要进一步操纵:

Name   ListOfManagers     Role
NULL   Jack, John, Louise Manager
James  NULL               Employee
Helen  NULL               Employee
Louise NULL               Employee

谢谢。

1 个答案:

答案 0 :(得分:3)

您可以使用XML PATHRole特定过滤器。

<强> SQL Fiddle

示例数据

CREATE TABLE Employee
    ([ID] int, [Name] varchar(6), [Role] varchar(8));

INSERT INTO Employee
    ([ID], [Name], [Role])
VALUES
    (1, 'Jack', 'Manager'),
    (2, 'John', 'Manager'),
    (3, 'James', 'Employee'),
    (4, 'Helen', 'Employee'),
    (5, 'Tony', 'Manager'),
    (6, 'Louise', 'Employee');

<强>查询

SELECT DISTINCT STUFF((
SELECT ',' + Name 
FROM Employee E2
WHERE (E1.Role = 'Manager' OR E1.ID = E2.ID)
ORDER BY ID ASC
FOR XML PATH('')
),1,1,'') as Name,Role
FROM Employee E1

<强>输出

Name    Role
Helen   Employee
Jack,John,James,Helen,Tony,Louise   Manager
James   Employee
Louise  Employee

您甚至可以选择UNION 2个不同的一组用于管理员GROUP BY和一个用于员工,并且仅在管理员查询中使用XML路径。

修改

根据更新后的问题,您可以像这样使用UNION ALL ..

<强> SQL Fiddle

<强>查询

SELECT
NULL as Name,
STUFF((
    SELECT ',' + Name 
    FROM Employee E2
    WHERE E2.Role = E1.Role
    ORDER BY ID ASC
    FOR XML PATH('')
    ),1,1,'') as ListofManagers,
Role
FROM Employee E1
WHERE Role = 'Manager'
GROUP BY Role

UNION ALL 

SELECT Name,NULL,Role
FROM Employee
WHERE Role = 'Employee'

<强>输出

|   Name | ListofManagers |     Role |
|--------|----------------|----------|
| (null) | Jack,John,Tony |  Manager |
|  James |         (null) | Employee |
|  Helen |         (null) | Employee |
| Louise |         (null) | Employee |