如何使用STRING_AGG将某些值分组为一行?

时间:2019-09-09 13:33:47

标签: sql sql-server tsql sql-server-2017

当所有列都相同但一列时,我想将几​​个lignes分组为一个。这是一个例子:

ID  |  Name  | CP  | Job
-----------------------------
1   |  Muse  | 13  | Job1
1   |  Muse  | 13  | Job2
1   |  Muse  | 13  | Job3
2   |  Tort  | 51  | Job4
2   |  Tort  | 51  | Job5

我想要:

ID  |  Name  | CP  | Job
-----------------------------
1   |  Muse  | 13  | Job1, Job2, Job3
2   |  Tort  | 51  | Job4, Job5

我尝试通过这种方式使用STRING_AGG:

SELECT ID, Name, CP, STRING_AGG(Job, ',')
FROM myTable
GROUP BY ID, Name, CP, Job
ORDER BY ID

我已经读过:https://database.guide/how-to-return-query-results-as-a-comma-separated-list-in-sql-server/

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

实际上,我只是一个人发现...。我不需要按工作分组:

Message

答案 1 :(得分:1)

一个有趣的发现,以及有关使用STRING_AGG的一些知识。如果您需要以任何特定顺序返回的新作业列中的项目,则可以利用WITHIN GROUP

-- Sample data with the inserts rearranged in random order
DECLARE @myTable TABLE 
(
  ID     INT,
  [Name] VARCHAR(100),
  CP     INT,
  Job    VARCHAR(100)
);

INSERT @myTable
VALUES
(1,'Muse',13,'Job3'),
(1,'Muse',13,'Job1'),
(1,'Muse',13,'Job2'),
(2,'Tort',51,'Job5'),
(2,'Tort',51,'Job4');

-- STRING_AGG ordering NOT guaranteed
SELECT ID, Name, CP, Job = STRING_AGG(Job, ',')
FROM @myTable
GROUP BY ID, Name, CP
ORDER BY ID;

-- STRING_AGG ordering IS guaranteed    
SELECT ID, Name, CP, job = STRING_AGG(Job, ',') WITHIN GROUP (ORDER BY Job)
FROM @myTable
GROUP BY ID, Name, CP
ORDER BY ID;

未排序的STRING_AGG结果:

ID          Name        CP          Job
----------- ----------- ----------- ------------------
1           Muse        13          Job3,Job1,Job2
2           Tort        51          Job5,Job4

未排序的STRING_AGG结果:

ID          Name        CP          job
----------- ----------- ----------- ------------------
1           Muse        13          Job1,Job2,Job3
2           Tort        51          Job4,Job5