2016-12-14 5 views
0

私のデータの形式は次のとおりです。SQL Serverの複雑なピボットテーブルクエリ

Customer_ID Order_ID Product_Sub-Category Product Name 
=========== ======== ==================== ============ 
A00001  20001A Vegetables   Onions 
A00001  20001A Vegetables   Garlic 
A00002  20001B Fruits    Apples 
A00002  20001B Fruits    Oranges 
A00002  20001B Vegetables   Spinach 
A00003  20001C Dairy    Milk 
A00003  20001C Dairy    Cheese 
A00004  20001D Meats    Lamb Chops 
A00004  20001D Meats    T-bone Steak 
A00004  20001D Dairy    Yoghurt 
A00004  20001D Fruits    Grapes 
A00004  20001D Vegetables   Garlic 

私は以下のフォーマットに変換する必要があります。

Customer_ID Order_ID Vegetables  Fruits   Dairy  Meats 
=========== ======== ==========  ======   =====  ===== 
A00001  20001A Onions, Garlic 
A00002  20001B Spinach  Apples, Oranges 
A00003  20001C         Milk, Cheese  
A00004  20001D Garlic   Grapes   Yoghurt  Lamb Chops, T-bone Steak 

これはあなたがしたいか動的行く必要があると仮定すると、SQLクエリ

+0

ご迷惑をおかけしました。 –

+2

はい、できます。はい、それはピボットです。どのような試みをしましたか? – Santi

+0

ブーム - https://msdn.microsoft.com/en-us/library/ms177410.aspx、次の質問? – Anand

答えて

0

で行うことができる場合は私に知らせてください。

EDIT - 戻り値

enter image description here

パフォーマンス

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([Product_Sub-Category]) From YourTable Order by 1 For XML Path('')),1,1,'') 
Select @SQL = ' 
Select [Customer_ID],[Order_ID],' + @SQL + ' 
    From (
     Select A.Customer_ID 
       ,A.Order_ID 
       ,A.[Product_Sub-Category] 
       ,C.String 
     From (Select Distinct Customer_ID,Order_ID,[Product_Sub-Category] From YourTable) A 
     Cross Apply (
         Select String=Stuff((Select Distinct '','' +[Product Name] 
              From YourTable 
              Where Customer_ID = A.Customer_ID 
               and Order_ID = A.Order_ID 
               and [Product_Sub-Category] = A.[Product_Sub-Category] 
              For XML Path ('''')),1,1,'''') 
        ) C 
     ) A 
Pivot (Max(String) For [Product_Sub-Category] in (' + @SQL + ')) p' 
Exec(@SQL); 

ためのSELECT DISTINCTを追加しました。それが助け場合は、あなたは、SQLを動的に必要としない場合次のようになります。

Select [Customer_ID],[Order_ID],[Dairy],[Fruits],[Meats],[Vegetables] 
    From (
     Select A.Customer_ID 
       ,A.Order_ID 
       ,A.[Product_Sub-Category] 
       ,C.String 
     From (Select Distinct Customer_ID,Order_ID,[Product_Sub-Category] From YourTable) A 
     Cross Apply (
         Select String=Stuff((Select Distinct ',' +[Product Name] 
               From YourTable 
               Where Customer_ID=A.Customer_ID 
               and Order_ID=A.Order_ID 
               and [Product_Sub-Category]=A.[Product_Sub-Category] 
               For XML Path ('')),1,1,'') 
        ) C 
     ) A 
Pivot (Max(String) For [Product_Sub-Category] in ([Dairy],[Fruits],[Meats],[Vegetables])) p