2016-12-14 88 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

做假設你想要或需要去動態。

編輯 - 增加了一個SELECT DISTINCT績效

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); 

返回

enter image description here

如果有幫助,如果你不需要動態的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