Query for comma-separated ids to comma-separated values

后端 未结 5 1534
终归单人心
终归单人心 2021-01-03 03:16

I have 2 tables

Departments

ID  Dept
---------
1   HR
2   Accts
3   IT

Employee

I         


        
5条回答
  •  鱼传尺愫
    2021-01-03 03:40

    DECLARE @Departments TABLE 
    (
      ID INT PRIMARY KEY, 
      Dept VARCHAR(32) NOT NULL UNIQUE
    );
    
    DECLARE @Employees TABLE
    (
      ID INT PRIMARY KEY,
      Name NVARCHAR(64) NOT NULL,
      Depts VARCHAR(255) NOT NULL
    );
    
    INSERT @Departments VALUES 
      (1,'HR'),  (2,'Accts'),  (3,'IT');
    
    INSERT @Employees VALUES
      (1,'Kevin','2,1'), (2,'Michelle','1'),
      (3,'Troy','1,3'),  (4,'Rheesa','2,3,1');
    
    SELECT ID, Name, Depts = STUFF((SELECT ',' + d.Dept 
        FROM @Departments AS d
        INNER JOIN @Employees AS ei
        ON ',' + ei.Depts + ',' LIKE '%,' + CONVERT(VARCHAR(12), d.id) + ',%'
        WHERE ei.ID = e.ID
        ORDER BY Dept
        FOR XML PATH, TYPE).value('.[1]', 'nvarchar(max)'), 1, 1, '')
    FROM @Employees AS e
    ORDER BY ID;
    

    The results don't quite match your required results, as the ordering is deterministic (ordered by department name):

    ID      Name        Depts
    ----    --------    ----
    1       Kevin       Accts,HR
    2       Michelle    HR
    3       Troy        HR,IT
    4       Rheesa      Accts,HR,IT
    

    If you want them ordered by the appearance in the comma-separated list, just change:

    ORDER BY Dept
    

    To:

    ORDER BY CHARINDEX( ',' + CONVERT(VARCHAR(12), d.id) + ',', ',' + ei.Depts + ',')
    

    Results:

    ID      Name        Depts
    ----    --------    ----
    1       Kevin       Accts,HR
    2       Michelle    HR
    3       Troy        HR,IT
    4       Rheesa      Accts,IT,HR -- this is the only one affected as it turns out
    

    However, in reality, you should normalize your database. This is an absolute nightmare.

提交回复
热议问题