在SQL中将单行的多行表组合在一起

时间:2012-11-20 10:25:35

标签: sql sql-server sql-server-2008

我的表格如下:

Ticket   Comment   UpdatedBy

100      Text 1     23
100      Text 2     24
100      Text 3     25
100      Text 4     26

我可以在一行表中将其作为(票证对所有行都相同)

Ticket   Comment

100      23 Said Text 1 - 24 Said Text 2 -  25 Said Text 3 - 26 Said Text 4

通过一些SQL查询?(Sql Server 2008)

2 个答案:

答案 0 :(得分:2)

您可以使用FOR XML PATH

SELECT Ticket, 
  STUFF((SELECT distinct ' - ' + cast(UpdatedBy as varchar(20)) + ' ' + comment
              from yourtable t2
              where t1.Ticket = t2.Ticket
            FOR XML PATH(''), TYPE

            ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') comments
from yourtable t1
group by ticket

请参阅SQL Fiddle with Demo

结果:

| TICKET |                                       COMMENTS |
-----------------------------------------------------------
|    100 |  23 Text 1 - 24 Text 2 - 25 Text 3 - 26 Text 4 |

答案 1 :(得分:0)

你可以这样做:

SELECT ticketno
     ,  STUFF((SELECT ' - ' + CAST(updateby AS VARCHAR) + ' said ' + comment  
         FROM tickets 
         WHERE (ticketno = t.ticketno) 
         FOR XML PATH ('')
      ),1,3,'') AS Comments
FROM tickets t
GROUP BY ticketno

Fiddle Example