TSQL-特定列的逗号分隔值

时间:2018-10-14 20:51:30

标签: sql-server tsql string-aggregation

我正在解决一个具有以下表定义的SQL Table的问题:

UniqueID    GroupID   DepartmentID
-----------------------------------
    1          2      D005
    2          2      D006
    3          2      D007
    4          5      D002
    5          1      D006
    6          3      D001
    7          3      D009
    8          3      D002
    9          3      D004
   10          3      D006

此表存储属于特定组的不同部门的信息。

我正在寻找一个简单且优化的查询,该查询针对各组以逗号分隔的值(在同一行中)输出部门列表 输出应如下所示:

GroupID      DepartmentList
-----------------------------
   2         D005,D006,D007
   5         D002
   1         D006
   3         D001,D009,D002,D004,D006

1 个答案:

答案 0 :(得分:1)

我使用了下表定义。

IF EXISTS(SELECT * FROM [sys].[objects] WHERE [object_id]=OBJECT_ID(N'Table1') AND [TYPE]=N'U')
DROP TABLE Table1
; 

CREATE TABLE Table1
(
  [UniqueID] [int]
, [GroupID] [int]
, [DepartmentID] [varchar](4) NULL
);

INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(1, 2, 'D005');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(2, 2, 'D006');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(3, 2, 'D007');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(4, 5, 'D002');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(5, 1, 'D006');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(6, 3, 'D001');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(7, 3, 'D009');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(8, 3, 'D002');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(9, 3, 'D004');
INSERT INTO Table1 ([UniqueID], [GroupID], [DepartmentID]) VALUES(10, 3, 'D006');

要在一条语句中运行它,我使用了CTE和从值中选择的内容。然后,我使用了STUFF函数来连接字符串值。

WITH
source_data
AS
(
    SELECT Table1.* FROM (VALUES
      ( 1, 2, 'D005')
    , ( 2, 2, 'D006')
    , ( 3, 2, 'D007')
    , ( 4, 5, 'D002')
    , ( 5, 1, 'D006')
    , ( 6, 3, 'D001')
    , ( 7, 3, 'D009')
    , ( 8, 3, 'D002')
    , ( 9, 3, 'D004')
    , ( 10, 3, 'D006')
    ) Table1 ([UniqueID], [GroupID], [DepartmentID]) 
)
SELECT DISTINCT
      [GroupID]
    , [DepartmentList] = STUFF
    ( 
        (
            SELECT 
                ',' + id2.[DepartmentID] 
            FROM 
                source_data AS id2
            WHERE 
                id1.[GroupID] = id2.[GroupID]
            GROUP BY 
                id2.[DepartmentID]
            FOR XML PATH(''), TYPE
        ).value('.', 'varchar(max)')
        ,1,1,''
    )
FROM 
    source_data AS id1

db<>fiddle

结果:

screenshot