SQL Server - 将行组合到每个客户的一个字段中

时间:2017-10-19 15:20:28

标签: sql sql-server

在SQL Server 2012上,当我运行时:

SELECT Customer, Fruit
FROM Customers_DB

我得到以下输出:

| Customer      | Fruit     |
| A0001         | Apple     |
| A0001         | Pear      |
| A0002         | Banana    |
| A0003         | Pear      |
| A0004         | Grape     |
| A0004         | Apricot   |

如何动态实现以下输出?

| Customer      | Fruit           |
| A0001         | Apple + Pear    |
| A0002         | Banana          |
| A0003         | Pear            |
| A0004         | Apricot + Grape |

我注意到水果是按字母顺序连接的(可能是Coalesce' d。)

1 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

Select Customer, 
    stuff((select ' + '+Fruit from #customer_db c where c.customer = c1.customer order by Fruit for xml path('')),1,3,'') as Fruit
from #customer_db c1
group by customer

输出如下:

+----------+-----------------+
| Customer |      Fruit      |
+----------+-----------------+
| A0001    | Apple + Pear    |
| A0002    | Banana          |
| A0003    | Pear            |
| A0004    | Apricot + Grape |
+----------+-----------------+

如果您使用的是SQL Server 2017或SQL Azure,则可以使用String_agg