如何在sql中将多个varchar行合并为一行

时间:2014-07-31 07:45:55

标签: merge

我有以下来源要求 来源

No  note_num    note_lines  Notes
1234567 21  1   Called xyz @ the FA and confirmed that we paid   
1234567 21  2   income to the client on the 01.01.9999. This      
1234567 21  3   amounted to £250.00 nett. I have confirmed that
1234567 21  4   I will arrange for documents confirming this to be
1234567 21  5   sent out to her. Referred back to Kirk in order   
1234567 21  6   to amend income slices for the designation.       

我需要目标输出如下

No  Notes
1234567 Called xyz @ the FA and confirmed that we paid income to the client on the 01.01.9999. This amounted to £250.00 nett. I have confirmed that I will arrange for documents confirming this to be sent out to her. Referred back to Kirk in order to amend income slices for the designation.

1 个答案:

答案 0 :(得分:0)

一种简单的方法是使用FOR XML PATH,它已成为SQL Server中GROUP_CONCAT的标准替代品;

WITH cte AS (SELECT DISTINCT no FROM mytable)
SELECT no, 
    STUFF(
    (
      SELECT CAST(' ' as varchar(max)) + notes
      FROM mytable
      WHERE mytable.no = cte.no
      ORDER BY note_lines
      FOR XML PATH('')
    ), 1, 1, '')
FROM
    cte
ORDER BY
    no ASC;

An SQLfiddle to test with