2017-10-19 12 views
1

を行を組み合わせる: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」)に連結されていることに注意してください。

+0

httpsを使用することができます/stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005 –

+0

これは何千回も質問され、回答されています。 –

+0

@SeanLangeそれでは、孤独な質問と回答を投稿したのはなぜですか? –

答えて

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

関連する問題