在SQL服务器中基于Group By连接行

时间:2014-03-28 11:28:54

标签: sql sql-server concatenation

我有一张表,其中包含人们针对工号编号的笔记。该数据取自旧系统,该系统将每行文本存储为新的表行。我想要做的是将每一行连接在一起,为每个作业编号形成一个字符串。

所以下表

JobNo | Line | Notes  
C1234 |  1   | blah blah blah.......  
C1234 |  2   | blah blah blah.....  
C1234 |  3   | blah blah blah.  
C1235 |  1   | blah blah blah blah blah blah.  
C1236 |  1   | blah blah blah....  

会变成

JobNo | Notes  
C1234 | blah blah blah....... blah blah blah..... blah blah blah.  
C1235 | blah blah blah blah blah blah.  
C1236 | blah blah blah....  

1 个答案:

答案 0 :(得分:0)

如果它的TSQL尝试将STUFFFOR XML PATH一起使用: -

(注意这只适用于sql server 2005以后)

SELECT
   JobNo,
   STUFF(
     (SELECT ' ' + Notes
      FROM MyTable
      WHERE JobNo = a.JobNo
      FOR XML PATH (''))
      , 1, 1, '')  AS URLList
FROM MyTable AS a
GROUP BY JobNo

请参阅此 SQL FIDDLE 工作示例